从服务器指定路径下载文件
发表于:2022-04-11 | 分类: 前端 后端
字数统计: 324 | 阅读时长: 1分钟 | 阅读量:

从服务器路径 / 本地指定路径下载文件

前端(普通blod下载方式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//点击下载
downloadInfo() {
this.axiosFun() //axios请求
.then(function (response) {
var blob = new Blob([response], { type: "application/x-xls" }); //创建一个blob对象
var a = document.createElement("a"); //创建一个<a></a>标签
a.href = URL.createObjectURL(blob); // response is a blob
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var contentDisposition = decodeURL(res.headers['content-disposition'])
var result = patt.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g,'')
a.download = fileName; //文件名称
a.style.display = "none";
document.body.appendChild(a);
a.click();
a.remove();
// this.$refs.upload.clearFiles()
})
.catch(function (err) {
console.log(err);
});
},

后端

controller 和 service接口太过简单, 直接 Impl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public void exportErr(HttpServletResponse response, String tmpId) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File file = new File("文件在服务器的路径");
String fileName = new String(file.getName().getBytes("gb2312"),"ISO8859-1");
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition","attachment;filename=" + fileName);
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf))>0){
outputStream.write(buf,0,len);
}
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
//别忘了关闭流
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null){
try {
outputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}

结束

上一篇:
前端展示文件流图片
下一篇:
NodeJs换镜像源