android volley 上传文件

1. 实现 multipart/form-data ,不借助第三方库

  • VolleyMultipartRequest.java
    • CLASS VolleyMultipartRequest
    • CLASS VolleyMultipartRequest.DataPart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package net.simplifiedlearning.androiduploadimage;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by Belal on 10/24/2017.
 */

public class VolleyMultipartRequest extends Request<NetworkResponse> {
        

  private final String twoHyphens = "--";
  private final String lineEnd = "\r\n";
  private final String boundary = "apiclient-" + System.currentTimeMillis();

  private Response.Listener<NetworkResponse> mListener;
  private Response.ErrorListener mErrorListener;
  private Map<String, String> mHeaders;


  public VolleyMultipartRequest(int method, String url,
                  Response.Listener<NetworkResponse> listener,
                  Response.ErrorListener errorListener) {
        
    super(method, url, errorListener);
    this.mListener = listener;
    this.mErrorListener = errorListener;
  }

  @Override
  public Map<String, String> getHeaders() throws AuthFailureError {
        
    return (mHeaders != null) ? mHeaders : super.getHeaders();
  }

  @Override
  public String getBodyContentType() {
        
    return "multipart/form-data;boundary=" + boundary;
  }

  @Override
  public byte[] getBody() throws AuthFailureError {
        
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);

    try {
        
      // populate text payload
      Map<String, String> params = getParams();
      if (params != null && params.size() > 0) {
        
        textParse(dos, params, getParamsEncoding());
      }

      // populate data byte payload
      Map<String, DataPart> data = getByteData();
      if (data != null && data.size() > 0) {
        
        dataParse(dos, data);
      }

      // close multipart form data after text and file data
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      return bos.toByteArray();
    } catch (IOException e) {
        
      e.printStackTrace();
    }
    return null;
  }

  /**
   * Custom method handle data payload.
   *
   * @return Map data part label with data byte
   * @throws AuthFailureError
   */
  protected Map<String, DataPart> getByteData() throws AuthFailureError {
        
    return null;
  }

  @Override
  protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        
    try {
        
      return Response.success(
          response,
          HttpHeaderParser.parseCacheHeaders(response));
    } catch (Exception e) {
        
      return Response.error(new ParseError(e));
    }
  }

  @Override
  protected void deliverResponse(NetworkResponse response) {
        
    mListener.onResponse(response);
  }

  @Override
  public void deliverError(VolleyError error) {
        
    mErrorListener.onErrorResponse(error);
  }

  /**
   * Parse string map into data output stream by key and value.
   *
   * @param dataOutputStream data output stream handle string parsing
   * @param params       string inputs collection
   * @param encoding     encode the inputs, default UTF-8
   * @throws IOException
   */
  private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException {
        
    try {
        
      for (Map.Entry<String, String> entry : params.entrySet()) {
        
        buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
      }
    } catch (UnsupportedEncodingException uee) {
        
      throw new RuntimeException("Encoding not supported: " + encoding, uee);
    }
  }

  /**
   * Parse data into data output stream.
   *
   * @param dataOutputStream data output stream handle file attachment
   * @param data       loop through data
   * @throws IOException
   */
  private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {
        
    for (Map.Entry<String, DataPart> entry : data.entrySet()) {
        
      buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
    }
  }

  /**
   * Write string data into header and data output stream.
   *
   * @param dataOutputStream data output stream handle string parsing
   * @param parameterName  name of input
   * @param parameterValue   value of input
   * @throws IOException
   */
  private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
        
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.writeBytes(parameterValue + lineEnd);
  }

  /**
   * Write data file into header and data output stream.
   *
   * @param dataOutputStream data output stream handle data parsing
   * @param dataFile     data byte as DataPart from collection
   * @param inputName    name of data input
   * @throws IOException
   */
  private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException {
        
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
        inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
    if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
        
      dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
    }
    dataOutputStream.writeBytes(lineEnd);

    ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
    int bytesAvailable = fileInputStream.available();

    int maxBufferSize = 1024 * 1024;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        
      dataOutputStream.write(buffer, 0, bufferSize);
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    dataOutputStream.writeBytes(lineEnd);
  }

  class DataPart {
        
    private String fileName;
    private byte[] content;
    private String type;

    public DataPart() {
        
    }

    DataPart(String name, byte[] data) {
        
      fileName = name;
      content = data;
    }

    String getFileName() {
        
      return fileName;
    }

    byte[] getContent
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值