任何人都可以帮助我如何将 RequestParam Multipart 文件从控制器中的一种方法传递到另一种方法。
我从 JSP 中获取 3 个输入,其中 1 个我稍后在单击另一个按钮时需要,我希望该文件进行修改。 所以我在控制器中创建了 2 个方法 - 一个 - 接受 3 个 RequestParam 并将与 2 个 RequestParam 一起使用,另一种方法将在单击另一个按钮时触发,我想在其中访问第三个 RequestParam,它是一个 MultiPartFile。
我尝试将此 MultiPartFile 存储在 ClassLevel Variable 中,但在另一种方法中使用它时出现类似文件未找到的错误。 我还尝试从中获取输入流并将其存储在类级变量中,这工作正常,但是一旦读取输入流,它就会正确关闭,如果我单击按钮,我们就无法在同一个会话中再次使用它再次它会抛出错误。
所以我想要一种方法在不同的控制器方法中传递该文件,以便我可以从中获取 InputStream 我将单击按钮多少次。
这是控制器:
@PostMapping(value = "/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleForm(@RequestParam("email") String email, @RequestParam("pass") String pass, @RequestParam("file")MultipartFile excelFile, Model model) {
try {
------
}
}
@GetMapping(value = "/processFile")
public void processFile() {
try {
---
}
}
所以在handleForm中我得到文件 - excelFile,我想在processFile方法中使用它,但我无法在handleForm()方法中调用该方法,因为processFile()方法要在单独的按钮单击中调用
// Provide the path to store the Excel file
// A better way is to not hardcode the file name
final static String fileLocation = "/path/to/save/your-excel-file.xlsx";
@PostMapping(value = "/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleForm(
@RequestParam("email") String email,
@RequestParam("pass") String pass,
@RequestParam("file") MultipartFile excelFile,
Model model) {
//save uploaded file to given location
saveMultipartFile(excelFile);
}
//It would be nice to change this, the name of the uploaded file can be redirected to download and that file can be downloaded
@GetMapping(value = "/processFile")
public ResponseEntity<?> processFile() {
//convert file to org.springframework.core.io.Resource;
Resource resource = null;
try {
resource = new UrlResource(Paths.get(fileLocation).toUri());
} catch (IOException e) {
return ResponseEntity.internalServerError().build();
}
String contentType = "application/octet-stream";
String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";
return ResponseEntity
.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
.body(resource);
}
/**
* Save uploaded MultipartFile to the given location
* @param file
* @throws Exception
*/
public static void saveMultipartFile(MultipartFile file)
throws Exception {
byte[] bytes = file.getBytes();
Path targetLocation = Paths.get(fileLocation);
// Creates a directory by creating all nonexistent parent directories first.
Files.createDirectories(targetLocation.getParent());
// Writes bytes to a file for the given target location.
Files.write(targetLocation, bytes);
}