SpringBoot 如何实现文件上传和下载

发布时间 2023-12-04 18:15:36作者: Xproer-松鼠

一、文件上传——upload
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
文件上传
Spring Boot提供了Multipart文件上传的支持。Multipart是HTTP协议中的一种方式,用于支持文件上传。下面我们将介绍如何在Spring Boot中实现文件上传。

我们只需要在Controller方法中声明一个MultipartFile类型的参数即可接收上传的文件

1.1前端代码实现
使用的element-ui组件进行实现,这段代码的编写既有上传,也有下载,其中:src就是下载图片

<el-upload class="avatar-uploader"
action="/common/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
ref="upload">
<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
1.2后端代码实现
@PostMapping("/upload")
public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
//上传文件的根路径
String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
String originalFilename = file.getOriginalFilename(); // 文件的原始名称
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String extName = FileUtil.extName(originalFilename);// png
if (!FileUtil.exist(ROOT_PATH)) {
FileUtil.mkdir(ROOT_PATH); // 如果当前文件的父级目录不存在,就创建
}
originalFilename = System.currentTimeMillis() + suffix;
File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
// 存储文件到本地的磁盘里面去
file.transferTo(saveFile);
//返回文件的链接,这个链接就是文件的下载地址,这个下载地址就是我的后台提供出来的
String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
return Result.success(url);
}

二、文件下载——download
2.1 介绍
指将文件从服务器传输到本地计算机的过程。

通过浏览器进行文件下载,通常有两种表现形式:

以附件形式下载,弹出保存对话框,将文件保存到指定磁盘目录
直接在浏览器中打开
通过浏览器进行文件下载,本质上就是服务端将文件以流的形式写会浏览器的过程。

2.2 前端代码编写
<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
2.3 后端代码编写
第一种方式:原生的
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
//1. 输入流,通过输入流读取文件内容
FileInputStream fileInputStream = new FileInputStream(new File(ROOT_PATH + File.separator + fileName));
//2. response输出流,将文件写回浏览器
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
//3.关闭流
outputStream.close();
fileInputStream.close();
}

第二种方式:hutool工具类
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.1</version>
</dependency>
@GetMapping("/download/{fileName}")
@AuthAccess
public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
//以附件方式进行下载
//response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("", "UTF-8"));
String filePath = ROOT_PATH + File.separator + fileName;
if (!FileUtil.exist(filePath)) {
return;
}
byte[] bytes = FileUtil.readBytes(filePath);
OutputStream outputStream = response.getOutputStream();
// 数组是一个字节数组,也就是文件的字节流数组
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}

附件形式下载

response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("", "UTF-8"));

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/04/springboot-%e5%a6%82%e4%bd%95%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd-2/

欢迎入群一起讨论