springboot实现文件上传下载步骤
时间: 2023-10-14 13:10:16 浏览: 169
好的,针对您的问题,下面是SpringBoot实现文件上传下载的步骤:
1.引入相关依赖
```xml
<!-- 文件上传下载依赖 -->
<!-- 文件上传支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件上传下载支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 文件上传下载支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
```
2.编写文件上传接口
```java
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 设置文件存储路径
String filePath = "D:/upload/";
// 重新生成文件名
fileName = UUID.randomUUID() + suffixName;
// 创建文件路径
File dest = new File(filePath + fileName);
// 存储文件
file.transferTo(dest);
return "上传成功";
}
}
```
3.编写文件下载接口
```java
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
// 设置文件路径
String filePath = "D:/upload/";
// 设置文件名
String fileName = "test.txt";
// 获取文件对象
File file = new File(filePath + fileName);
// 创建字节输入流
InputStream in = new FileInputStream(file);
// 创建字节数组
byte[] bytes = new byte[in.available()];
// 将字节输入流读入字节数组
in.read(bytes);
// 创建HttpHeaders对象
HttpHeaders headers = new HttpHeaders();
// 设置下载文件名
headers.setContentDispositionFormData("attachment", fileName);
// 设置响应类型
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 封装响应结果
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
return responseEntity;
}
}
```
以上就是SpringBoot实现文件上传下载的步骤。如果您有其他问题需要咨询,欢迎继续提问。
阅读全文