我正在使用spring boot 2.我的新任务是文件上传。我已经做到了。但我被要求这样做而不向控制器方法添加额外的参数,如@RequestParam("文件")MultipartFile文件[]。我希望从请求中获取此信息,而不是添加此参数。
我该如何解决这个问题?
我正在添加我当前的代码。
@RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload( @RequestParam("files") MultipartFile files[]){
try {
String filePath="c:/temp/kk/";
StringBuffer result=new StringBuffer();
byte[] bytes=null;
result.append("Uploading of File(s) ");
for (int i=0;i<files.length;i++) {
if (!files[i].isEmpty()) {
bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+files[i].getOriginalFilename())));
stream.write(bytes);
stream.close();
result.append(files[i].getOriginalFilename() + " Ok. ") ;
}
else
result.append( files[i].getOriginalFilename() + " Failed. ");
}
return result.toString();
} catch (Exception e) {
return "Error Occured while uploading files." + " => " + e.getMessage();
}
}
答案 0 :(得分:0)
您可以从HttpRequest获取文件:
@RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public String handleFileUpload(HttpRequest request){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> yourFiles = multipartRequest.getFileMap();
return "All is Ok!";
}
答案 1 :(得分:0)
我的示例代码。
@RequestMapping(value = "/multiple/upload", method = RequestMethod.POST)
public @ResponseBody String test(@RequestParam(value = "files[]") List<MultipartFile> files,
HttpServletRequest req) {
MultipartFileWriter writer = new MultipartFileWriter();
String folderPath = "/file/";
for (MultipartFile file : files) {
writer.writeFile(file, folderPath, req);
}
return "success";
}