Mar*_*zak 5 java spring file-upload file spring-boot
To upload a file in spring boot one can use something like this:
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
Run Code Online (Sandbox Code Playgroud)
and it works fine.
My problem is how can I extend this code to get some kind of updates during upload. For example: one enent every 10% of completed upload. Is there any kind of mechanism which creates such events during upload? Can I overwrite some internal spring method to make it work?
要获取进度更新回调,请将以下 bean 添加到您的应用程序中:
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
final CommonsMultipartResolver cmr = new CommonsMultipartResolver();
cmr.setMaxUploadSize(10000000); // customize as appropriate
cmr.setDefaultEncoding("UTF-8"); // important to match in your client
cmr.getFileUpload().setProgressListener(
(long pBytesRead, long pContentLength, int pItems) -> {
// insert progress update logic here
});
return cmr;
}
Run Code Online (Sandbox Code Playgroud)
还将以下属性添加到您的应用程序属性中:
spring.http.multipart.enabled = false
Run Code Online (Sandbox Code Playgroud)
UTF-8注意:您的客户端应用程序与预期的内容编码相匹配(在本示例中)非常重要。如果没有,那么FileUpload将使用一个临时对象,而不是我们在上面代码中自定义的对象。这可能是一个错误,CommonsFileUploadSupport.java因为它将原始的所有其他成员复制FileUpload到临时成员中,忽略了侦听器。
| 归档时间: |
|
| 查看次数: |
4469 次 |
| 最近记录: |