springboot上传下载功能怎么实现
在Spring Boot中,可以使用MultipartFile接口来实现文件上传功能,使用ResponseEntity来实现文件下载功能。
文件上传功能的实现步骤如下:
在Controller中添加一个处理文件上传的方法,并使用@RequestParam注解来接收上传的文件参数。
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 处理文件上传逻辑
// ...
return "上传成功";
}
在application.properties或application.yml配置文件中添加文件上传相关的配置。
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
在前端页面中添加一个文件上传表单,并设置enctype属性为multipart/form-data。
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
文件下载功能的实现步骤如下:
在Controller中添加一个处理文件下载的方法,并使用PathVariable注解来接收文件名参数。
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
// 获取文件路径
String filePath = "path/to/file/" + filename;
// 创建文件资源对象
Resource fileResource = new FileSystemResource(filePath);
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
return ResponseEntity.ok()
.headers(headers)
.contentLength(fileResource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileResource);
}
在前端页面中添加一个下载按钮,并设置对应的下载链接。
<a th:href="@{/download/filename}" download>下载</a>
其中,filename为要下载的文件名。
以上就是Spring Boot中实现文件上传下载功能的基本步骤。具体实现根据具体需求可能会有所不同,可以根据需要进行调整。
阅读剩余
THE END