springboot实现文件上传和下载
时间: 2023-04-28 19:04:02 浏览: 87
Spring Boot可以通过MultipartFile实现文件上传和下载。
文件上传:
1. 在Controller中添加一个POST请求处理方法,使用@RequestParam注解获取上传的文件。
2. 使用MultipartFile的transferTo()方法将文件保存到指定的位置。
3. 返回上传成功的信息。
文件下载:
1. 在Controller中添加一个GET请求处理方法,使用@RequestParam注解获取要下载的文件名。
2. 使用FileInputStream读取文件内容,并将内容写入到HttpServletResponse的输出流中。
3. 设置HttpServletResponse的Content-Disposition头部信息,指定文件名和下载方式。
4. 返回null,告诉Spring Boot不需要渲染任何视图。
示例代码:
文件上传:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 保存文件到指定位置
file.transferTo(new File("D:/uploads/" + file.getOriginalFilename()));
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
文件下载:
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String filename) {
try {
// 读取文件内容
FileInputStream fis = new FileInputStream(new File("D:/uploads/" + filename));
byte[] content = new byte[fis.available()];
fis.read(content);
fis.close();
// 设置Content-Disposition头部信息
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
// 返回文件内容和头部信息
return new ResponseEntity<>(content, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)