在使用SpringBoot进行文件上传时,发现使用MultipartFile获取前端传的file一直为null,看了很多帖子一直说是springboot自带的org.springframework.web.multipart.MultipartFile和Multipart冲突。然后经过自己测试发现自己的并不是这个问题,后面发现是html中文件的name需要和中的value想对应。如下:
<input type="file" name="uploadFile" value="请选择文件进行上传">
@RequestParam(value = "uploadFile",required = false
前段代码:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件进行上传">
<input type="submit" value="上传">
</form>
Controller中的代码:
public @ResponseBody String multipleSave(@RequestParam(value = "uploadFile",required = false) MultipartFile[] files){
System.out.println("file" + files);
String fileName = null;
String msg = "";
if (files != null && files.length >0) {
for(int i =0 ;i< files.length; i++){
try {
fileName = files[i].getOriginalFilename();
byte[] bytes = files[i].getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("/tmp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
msg += "You have successfully uploaded " + "fileName";
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage();
}
}
return msg;
} else {
return "Unable to upload. File is empty.";
}
}
这样问题就解决了。