Springboot实现文件上传和下载
时间: 2024-05-13 17:15:08 浏览: 19
Spring Boot提供了很多方便的工具类和注解来实现文件上传和下载功能。
文件上传:
1. 在`pom.xml`中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 编写Controller:
```java
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String filePath = "D:\\uploads\\";
File dest = new File(filePath + fileName);
file.transferTo(dest);
return "上传成功";
}
}
```
3. 编写HTML页面:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
```
文件下载:
1. 在Controller中添加下载方法:
```java
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
String filePath = "D:\\uploads\\";
String fileName = "test.txt";
File file = new File(filePath + fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
2. 在HTML页面中添加下载链接:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<a href="/download">下载文件</a>
</body>
</html>
```
以上就是Spring Boot实现文件上传和下载的简单方法。