Spring MVC提供了方便的文件上传和下载功能,下面一一进行讲解。
文件上传
- 配置文件上传解析器:
在Spring配置文件中配置MultipartResolver,用于处理文件上传请求:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880"/> <!-- 设置最大上传文件大小 -->
</bean>
- 编写Controller处理文件上传请求:
编写Controller方法处理文件上传请求,使用@RequestParam注解接收MultipartFile类型的文件:
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
// 处理文件上传逻辑
return "uploadSuccess";
}
}
文件下载
- 编写Controller处理文件下载请求:
编写Controller方法处理文件下载请求,使用ResponseEntity返回文件内容:
@Controller
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
Resource resource = new FileSystemResource("path/to/file.pdf"); // 文件路径
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.pdf");
return ResponseEntity.ok().headers(headers).body(resource);
}
}
原文链接: https://blog.csdn.net/2401_82884096/article/details/138025407