Spring Boot提供了很多方便的方式来实现上传下载图片的功能,可以使用Spring Boot的MVC模块的MultipartFile对象来处理文件上传,也可以使用原生的Servlet API来处理文件下载。
以下是一个简单的示例,演示如何使用Spring Boot实现上传和下载图片功能。
- 上传图片
添加前端页面(HTML):
code
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file" required="required"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
添加Controller处理上传请求:
code
@Controller
public class UploadController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// 上传到指定目录下
String path = "/path/to/your/folder/";
File localFile = new File(path + file.getOriginalFilename());
file.transferTo(localFile);
return "success";
}
}
- 下载图片
添加前端页面(HTML):
code
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>下载图片</title>
</head>
<body>
<form th:action="@{/download}" method="post">
<input type="text" name="filename" required="required"/><br/>
<input type="submit" value="下载"/>
</form>
</body>
</html>
添加Controller处理下载请求:
code
@Controller
public class DownloadController {
@PostMapping("/download")
public ResponseEntity<Resource> download(@RequestParam("filename") String filename) throws IOException {
// 设定下载文件的路径
String path = "/path/to/your/folder/";
File file = new File(path + filename);
if (!file.exists()) {
throw new FileNotFoundException("File not found: " + filename);
}
// 构造Resource对象
Resource resource = new UrlResource(file.toURI());
// 构造响应体
return ResponseEntity.ok()
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
在上面的例子中,使用原生的Servlet API实现文件下载,构造Spring ResponseEntity对象返回下载的文件,其中HttpHeaders.CONTENT_DISPOSITION表示指定文件下载时的附件名称。