SpringBoot 文件上传和下载
时间: 2024-12-28 16:23:47 浏览: 9
### Spring Boot 实现文件上传和下载功能
#### 添加项目依赖
为了支持文件上传和下载,在 `pom.xml` 文件中需引入必要的依赖项,主要包括用于构建Web应用程序的 `spring-boot-starter-web` 和模板引擎 Thymeleaf 的启动器 `spring-boot-starter-thymeleaf`。
```xml
<dependencies>
<!-- Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf Template Engine -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
```
#### 配置文件设置
在 `application.properties` 或者 `application.yml` 中配置文件上传的相关属性,比如最大允许上传的文件大小以及临时存储位置等[^3]:
```properties
# application.properties example
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
file.upload-dir=/tmp/uploads/
```
#### 创建控制器处理请求
定义一个控制类来管理HTTP POST 请求以接收并保存上传的文件;同时也提供 GET 方法用来响应用户的下载需求。这里展示了一个简单的例子:
```java
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileController {
private static String UPLOAD_DIR = "uploads/";
@PostMapping("/upload") // Handle file upload request
public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
try {
Path copyLocation = Paths.get(UPLOAD_DIR + File.separator + file.getOriginalFilename());
Files.copy(file.getInputStream(), copyLocation);
model.addAttribute("msg", "You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
@GetMapping("/download/{fileName:.+}") // Serve files as media types based on their extensions.
@ResponseBody
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {
Path path = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
Resource resource = new FileSystemResource(path.toFile());
if (!resource.exists()) throw new FileNotFoundException("Could not find the requested file!");
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"");
MediaType contentType = Files.probeContentType(path);
return ResponseEntity.ok()
.headers(headers)
.contentType(contentType != null ? MediaType.parseMediaType(contentType) : MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
```
上述代码片段展示了如何利用Spring MVC框架中的注解简化开发过程,并通过 `MultipartFile` 接口获取客户端发送过来的数据流完成文件写入操作。对于下载部分,则是读取指定路径下的目标资源并通过 HTTP 响应头告知浏览器应该如何对待接收到的内容(即提示用户打开或另存为对话框)。此外还加入了异常捕获机制确保程序健壮性。
阅读全文