一、multipart/mixed 请求
multipart/mixed 和 multipart/form-date 都是多文件上传的格式。区别在于,multipart/form-data 是一种特殊的表单上传,其中普通字段的内容还是按照一般的请求体构建,文件字段的内容按照 multipart 请求体构建,后端在处理 multipart/form-data 请求的时候,会在服务器上建立临时的文件夹存放文件内容,可参看这篇文章。而 multipart/mixed 请求会将每个字段的内容,不管是普通字段还是文件字段,都变成 Stream 流的方式去上传,因此后端在处理 multipart/mixed 的内容时,必须从 Stream流中处理。
二、Servlet 处理 multipart/mixed 请求
代码语言:javascript复制 Part signPart = request.getPart(Constants.SIGN_KEY);
Part appidPart = request.getPart(Constants.APPID_KEY);
Part noncestrPart = request.getPart(Constants.NONCESTR_KEY);
Map<String, String[]> paramMap = new HashMap<>(8);
paramMap.put(signPart.getName(), new String[]{stream2Str(signPart.getInputStream())});
paramMap.put(appidPart.getName(), new String[]{stream2Str(appidPart.getInputStream())});
paramMap.put(noncestrPart.getName(), new String[]{stream2Str(noncestrPart.getInputStream())});
代码语言:javascript复制 private String stream2Str(InputStream inputStream) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
三、SpringMVC 处理 multipart/mixed 请求
代码语言:javascript复制 @ResponseBody
@RequestMapping(value = {"/token/user/uploadImage.yueyue", "/token/user/uploadImage"}, method = {RequestMethod.POST, RequestMethod.GET})
public AjaxList uploadImage(
@RequestPart (required = false) String token,
@RequestPart (required = false) String sign,
@RequestPart (required = false) String appid,
@RequestPart (required = false) String noncestr,
@RequestPart MultipartFile avatar, HttpServletRequest request) {
}