服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android使用Volley框架定制PostUploadRequest上传文件

Android使用Volley框架定制PostUploadRequest上传文件

2022-09-07 15:46Raindus Android

这篇文章主要为大家详细介绍了Android使用Volley框架定制PostUploadRequest上传文件或图片,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

发现问题

项目中有发表动态的功能,该功能可以将文本和图片上传至服务器。
Volley通过定制PostUploadRequest实现文件上传的功能,本文以一张图片上传为例。

数据格式

以下为项目中图片上传实例的数据格式
多张图片上传可通过添加——WebKitFormBoundary 内容实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
POST /CloudLife/user/social HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzayymBT8Owg2UzBR
Referer: http://localhost/CloudLife/upload.jsp
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Cookie: CLOUD_LIFE=03F21B9A9D9B4FF2BF443290A9CD8E2C; USER=18060506304; JSESSIONID=C4AB532929FA43230FA193A98197F962
Content-Length: 12444
 
------WebKitFormBoundaryzayymBT8Owg2UzBR
Content-Disposition: form-data; name="text"
 
发表的圈子内容
------WebKitFormBoundaryzayymBT8Owg2UzBR
Content-Disposition: form-data; name="file"; filename="这里是文件名"
Content-Type: image/png
这里空一行 接下来是二进制图片文件内容
------WebKitFormBoundaryzayymBT8Owg2UzBR--
这里为空白的一行

总共有加上结尾行,有五行,图片的二进制数,整个算一行;下面来分析下:

1、第一行:”–” + boundary + “\r\n” ;
文件上传在提交数据的开始标志不变;

2、第二行:Content-Disposition: form-data; name=”参数的名称”; filename=”上传的文件名” + “\r\n”

3、第三行:Content-Type: 文件的 mime 类型 + “\r\n”
这一行是文件上传必须要的,而普通的文字提交可有可无,mime 类型需要根据文档查询;

4、第四行:”\r\n”

5、第五行文件的二进制数据 + “\r\n”:
结尾行:”–” + boundary + “–” + “\r\n”
可以同时上传多个文件,上传多个文件的时候重复1、2、3、4、5步,在最后的一个文件的末尾加上统一的结束行。

上传的图像实体类

?
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
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
 
/*
 * 上传的图像实体类
 * */
public class FormImage {
 
 // 参数的名称
 private String mName;
 
 // 文件名
 private String mFileName;
 
 // 文件的 mime,需要根据文档查询
 private String mMime;
 
 // 需要上传的图片资源,因为这里测试为了方便起见,直接把 bitmap 传进来,真正在项目中一般不会这般做,
 // 而是把图片的路径传过来,在这里对图片进行二进制转换
 private Bitmap mBitmap = null;
 
 public FormImage(Bitmap bitmap) {
 this.mBitmap = bitmap;
 }
 
 public String getName() {
 return "file";
 }
 
 public String getFileName() {
 return "add.png";
 }
 
 // 对图片进行二进制转换
 public byte[] getValue() {
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
 return bos.toByteArray();
 }
 
 // 因为我知道是 png 文件,所以直接根据文档查的
 public String getMime() {
 return "image/png";
 }
}

定制PostUploadRequest

?
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
 
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
 
import android.util.Log;
 
/*
 * 发送文件的volley
 * post请求 Cookie
 * */
public class PostUploadRequest extends Request<JSONObject> {
 
 private Map<String, String> sendHeader = new HashMap<String, String>();
 
 // 正确数据的时候回掉用
 private Response.Listener<JSONObject> mListener;
 
 // 请求 数据通过参数的形式传入
 private String content;
 private FormImage mImage;
 
 // 数据分隔线
 private String BOUNDARY = "----CloudLifeUpLoadImage";
 private String MULTIPART_FORM_DATA = "multipart/form-data";
 
 public PostUploadRequest(String url, String text, FormImage Item, Response.Listener<JSONObject> listener,Response.ErrorListener errorListener) {
 
 super(Method.POST, url, errorListener);
 this.mListener = listener;
 setShouldCache(false);
 mImage = Item;
 content = text;
 
 // 设置请求的响应事件,因为文件上传需要较长的时间,所以在这里加大了,设为5秒
 setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
  DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
 }
 
 /*
 * 这里开始解析数据
 * @param response
 *  Response from the network
 * @return
 * */
 @Override
 protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
 try {
  // 防止中文乱码
  @SuppressWarnings("deprecation")
  String jsonString = new String(response.data, HTTP.UTF_8);
 
  JSONObject jsonObject = new JSONObject(jsonString);
 
  Log.w("upLoad", "jsonObject " + jsonObject.toString());
 
  return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
 } catch (UnsupportedEncodingException e) {
  return Response.error(new ParseError(e));
 } catch (JSONException je) {
  return Response.error(new ParseError(je));
 }
 }
 
 /*
 * 回调正确的数据
 * @param response
 *  The parsed response returned by
 * */
 @Override
 protected void deliverResponse(JSONObject response) {
 mListener.onResponse(response);
 }
 
 @Override
 public Map<String, String> getHeaders() throws AuthFailureError {
 return sendHeader;
 }
 
 public void setSendCookie(String cookie) {
 sendHeader.put("Cookie", cookie);
 }
 
 @Override
 public byte[] getBody() throws AuthFailureError {
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
 StringBuffer sb = new StringBuffer();
 
 if (content == null) {
  /**
  * 图片
  */
  /* 第一行 */
  // `"--" + BOUNDARY + "\r\n"`
  sb.append("--" + BOUNDARY + "\r\n");
 
  /* 第二行 */
  // Content-Disposition: form-data; name="参数的名称"; filename="上传的文件名" +
  // "\r\n"
  sb.append("Content-Disposition: form-data;");
  sb.append(" name=\"");
  sb.append(mImage.getName());
  sb.append("\"");
  sb.append("; filename=\"");
  sb.append(mImage.getFileName());
  sb.append("\"");
  sb.append("\r\n");
 
  /* 第三行 */
  // Content-Type: 文件的 mime 类型 + "\r\n"
  sb.append("Content-Type: ");
  sb.append(mImage.getMime());
  sb.append("\r\n");
 
  /* 第四行 */
  // "\r\n" 空白的一行
  sb.append("\r\n");
 
  try {
  bos.write(sb.toString().getBytes("utf-8"));
  /* 第五行 */
  // 文件的二进制数据 + "\r\n"
  bos.write(mImage.getValue());
  bos.write("\r\n".getBytes("utf-8"));
  } catch (IOException e) {
  e.printStackTrace();
  }
 
  /* 结尾行 */
  // `"--" + BOUNDARY + "--" + "\r\n"`
  String endLine = "--" + BOUNDARY + "--" + "\r\n";
  try {
  bos.write(endLine.toString().getBytes("utf-8"));
  } catch (IOException e) {
  e.printStackTrace();
  }
  Log.v("upLoad", "=====formImage====\n" + bos.toString());
  return bos.toByteArray();
 }
 /**
  * 文字
  */
 /* 第一行 */
 // `"--" + BOUNDARY + "\r\n"`
 sb.append("--" + BOUNDARY + "\r\n");
 
 /* 第二行 */
 // Content-Disposition: form-data; name="text" + "\r\n"
 sb.append("Content-Disposition: form-data;");
 sb.append(" name=\"");
 sb.append("text");
 sb.append("\"");
 sb.append("\r\n");
 
 /* 第三行 */
 // "\r\n" 空白的一行
 sb.append("\r\n");
 
 /* 第四行 */
 // 文本内容
 sb.append(content);
 sb.append("\r\n");
 
 if (mImage == null) {
  /* 结尾行 */
  // `"--" + BOUNDARY + "--" + "\r\n"`
  String endLine = "--" + BOUNDARY + "--" + "\r\n";
  try {
  bos.write(sb.toString().getBytes("utf-8"));
  bos.write(endLine.toString().getBytes("utf-8"));
  } catch (IOException e) {
  e.printStackTrace();
  }
  Log.v("upLoad", "=====formImage====\n" + bos.toString());
  return bos.toByteArray();
 } else {
  /**
  * 图片
  */
  /* 第一行 */
  // `"--" + BOUNDARY + "\r\n"`
  sb.append("--" + BOUNDARY + "\r\n");
 
  /* 第二行 */
  // Content-Disposition: form-data; name="参数的名称"; filename="上传的文件名" +
  // "\r\n"
  sb.append("Content-Disposition: form-data;");
  sb.append(" name=\"");
  sb.append(mImage.getName());
  sb.append("\"");
  sb.append("; filename=\"");
  sb.append(mImage.getFileName());
  sb.append("\"");
  sb.append("\r\n");
 
  /* 第三行 */
  // Content-Type: 文件的 mime 类型 + "\r\n"
  sb.append("Content-Type: ");
  sb.append(mImage.getMime());
  sb.append("\r\n");
 
  /* 第四行 */
  // "\r\n" 空白的一行
  sb.append("\r\n");
 
  try {
  bos.write(sb.toString().getBytes("utf-8"));
  /* 第五行 */
  // 文件的二进制数据 + "\r\n"
  bos.write(mImage.getValue());
  bos.write("\r\n".getBytes("utf-8"));
  } catch (IOException e) {
  e.printStackTrace();
  }
 
 }
 
 /* 结尾行 */
 // `"--" + BOUNDARY + "--" + "\r\n"`
 String endLine = "--" + BOUNDARY + "--" + "\r\n";
 try {
  bos.write(endLine.toString().getBytes("utf-8"));
 } catch (IOException e) {
  e.printStackTrace();
 }
 Log.v("upLoad", "=====formImage====\n" + bos.toString());
 return bos.toByteArray();
 }
 
 // Content-Type: multipart/form-data; boundary=----------8888888888888
 @Override
 public String getBodyContentType() {
 return MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY;
 }
}

实例

?
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
RequestQueue mQueue = SingleRequestQueue.getRequestQueue();
 
FormImage image;
if (imageUri != null) {
 Bitmap bitmap = null;
 try {// 将路径转化成bitmap
 bitmap=BitmapFactory.decodeStream(
  getContentResolver().openInputStream(imageUri));
 } catch (FileNotFoundException e1) {
 e1.printStackTrace();
 }
 image = new FormImage(bitmap);
} else
 image = null;
 
PostUploadRequest post = new PostUploadRequest(C.api.userIcon, null, image,
 new Response.Listener<JSONObject>() {
 @Override
 public void onResponse(JSONObject jsonObject) {
  try {
  //TODO
  } catch (JSONException e) {
  e.printStackTrace();
  }
 }
 }, new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {
  Log.e("VolleyError", error.getMessage(), error);
 }
 });
 
if (!customer.getCookie().equals("")) {
 // 向服务器发起post请求时加上cookie字段
 post.setSendCookie(customer.getCookie());
}
 
mQueue.add(post);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u010000110/article/details/72633430

延伸 · 阅读

精彩推荐