创建springboot文件,在pom.xml中配置依赖。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.6.5</version>
</dependency>
创建一个Controller类,实现下载接口。
@RestController
@RequestMapping("/api/download")
@Api(tags = "共同前缀:/api/download", description = "FileDownloadController")
@Slf4j
public class FileDownloadController {
//路径设置
//System.getProperty("user.dir")是所在项目的根目录
//"src/main/resources/static/images/"是项目内的存储路径
private static final String filePath = System.getProperty("user.dir")+"src/main/resources/static/images/";
//下载文件
//flag是时间戳形式的文件名(可以不是,具体看代码)
@GetMapping("/{flag}")
public void avatarPath(@PathVariable String flag , HttpServletResponse response){
//判断路径文件家是否存在
if(!FileUtil.isDirectory(filePath)){
FileUtil.mkdir(filePath);
}
OutputStream os;
List<String> fileNames = FileUtil.listFileNames(filePath);
String avatar = fileNames.stream().filter(name->name.contains(flag)).findAny().orElse("");
try{
if(StrUtil.isEmpty(avatar)){
response.addHeader("Content-Disposition", "attachment;filename"+ URLEncoder.encode(avatar, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(filePath + avatar);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
System.out.println("下载成功");
}
}catch (Exception e){
System.out.println("下载失败");
}
}
}
前端Vue设置按钮绑定点击事件,在method里面写函数。
拼接方式:后端端口号+下载controller的url+文件名。
<el-button @click="downloadFile">下载</el-button>
downloadFile: function () {
location.href = 'http://localhost:9090/api/download/' + this.content
}