目录
1 实例代码
以下代码都是经过测试可直接使用
@ApiOperation(value = "上传多文件", notes = "上传多文件")
@ApiResponses({
@ApiResponse(code = 503, message = "服务不可用"),
@ApiResponse(code = 404, message = "请求不存在"),
@ApiResponse(code = 200, message = "服务器成功返回"),
@ApiResponse(code = 501, message = "暂时没有实现"),
@ApiResponse(code = 400, message = "请求参数没填写好")})
@RequestMapping(value = "/uploadPictures", method = RequestMethod.POST)
public ResponseEntity<JSONArray> uploadPictures(List<MultipartFile> files) {
return new ResponseEntity<>(fileInfoService.uploadFiles(files), HttpStatus.OK);
}
@Override
public JSONArray uploadFiles(List<MultipartFile> file) throws ApiException {
JSONArray jsonArray=new JSONArray();
for (MultipartFile multipartFile : file) {
FileInfo fileInfo = this.uploadFile(multipartFile);
jsonArray.add(fileInfo.getId().toString());
}
return jsonArray;
}
@Override
public FileInfo uploadFile(MultipartFile multipartFile) throws ApiException {
Date date=new Date();
long time = date.getTime();
FileInfo fileInfo = new FileInfo();
byte[] bytes = new byte[0];
try {
bytes = multipartFile.getBytes();
} catch (IOException e) {
e.printStackTrace();
}
String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
String filePath = System.getProperty("user.home") + File.separator+"lcls"+File.separator+"fileInfo"+File.separator +time+"."+suffix;
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write(bytes, 0, bytes.length);
fileInfo.setFileRealName(multipartFile.getOriginalFilename());
fileInfo.setFileSysName(time+"."+suffix);
fileInfo.setFileType(multipartFile.getContentType());
fileInfo.setExtensions(suffix);
fileInfo.setFileSize((long) bytes.length);
fileInfo.setPath(filePath);
this.save(fileInfo);
return fileInfo;
}
2 遇到的坑
做到文件上传,单文件上传时一切正常,多文件时files参数一直为null,代码如下:
因为平时一直都使用swagger测试接口,之所以用swagger获取不到files,是因为swagger不支持在一个参数中上传文件数组,如果上传就会传递空值。踩坑踩了好久,但是在前端直接用form表单上传时可以的,建议测试多文件上传时用postman进行测试。