spring 文件上传

1、单文件上传

1
2
3
4
5
6
7
8
9
10
11
public JsonData uploadImageToServer(@RequestParam("file") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
File imageFile = new File("/home/data/" + file.getOriginalFilename());

FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
fileOutputStream.write(bytes);
fileOutputStream.close();

Optional<String> url = imageProcessor.push(file);
return JsonData.success(url.get());
}

直接用postman可以测试上传,需要注意: method要设置成post,header的ContentType要删除,一定要记得header中ContentType要删除,否则就会出现上传不了的问题。

2、多文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public JsonData multiUploadImageToServer(HttpServletRequest request) throws IOException {

List<String> retList = new ArrayList<>();
if (request instanceof MultipartHttpServletRequest) {
MultiValueMap<String, MultipartFile> multipartFileMultiValueMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
for (String key : multipartFileMultiValueMap.keySet()) {
List<MultipartFile> multipartFileList = multipartFileMultiValueMap.get(key);
if (CollectionUtils.isEmpty(multipartFileList)) {
continue;
}
for (MultipartFile multipartFile : multipartFileList) {
Optional<String> url = imageProcessor.push(multipartFile);
retList.add(url.get());
}
}
}

return JsonData.success(retList);
}

下图是postman测试的测试结果。多文件上传的主要在于把request转换成MultipartHttpServletRequest,并获取所有上传文件(MultipartFile集合),然后执行相应的上传操作。当然,对文件用postman测试依旧需要删除header的contentType,这个值你可能不主动设置,但是当你选择form-data的时候会自动帮你设置上,似乎有点disgusting~

image-20191113202115742