Axios 发送 post 请求下载文件 blob 流

 发布 : 2019-06-06  字数统计 : 477 字  阅读时长 : 2 分  分类 : 请求  浏览 :
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//fileDownload.js

import axios from 'axios';
/**
* 发送post请求下载文件,返回的为 blob 流
* @param {*} url 接口地址
* @param {*} data 参数
* @param {*} fileName 文件名
*/
export default async function fileDownload(url, data, fileName) {
axios.defaults.headers.post['Content-Type'] = 'application/json';
await axios({
method: 'post',
url: url,
data: JSON.stringify(data),
responseType: 'blob'
}).then((res) => {
const content = res.data;
const contentType = res.headers['content-type'] || "application/octet-stream"; // 处理浏览器兼容
const blob = new Blob([content], {type: contentType});
if ('download' in document.createElement('a')) { //非ie
const fileLink = document.createElement('a');
fileLink.download = fileName;
fileLink.style.display = 'none';
fileLink.href = URL.createObjectURL(blob);
document.body.appendChild(fileLink);
fileLink.click();
URL.revokeObjectURL(fileLink.href); // 释放URL 对象
document.body.removeChild(fileLink);
} else { //ie10+
navigator.msSaveBlob(blob, fileName);
}
})
}

//具体使用
import fileDownload from 'fileDownload';
fileDownload("url", "data", "fileName").then( () => {
//可以处理回调,例如下载状态
})



// 返回pdf 流并预览
export default async function pdfPreview(method, url, data, fileName) {
let open;
if ('download' in document.createElement('a')) {
open = window.open(); //防止拦截
}
axios.defaults.headers.post['Content-Type'] = 'application/json';
try {
await axios({
method: method,
url: url,
data: JSON.stringify(data),
responseType: 'blob'
}).then((res) => {
const content = res.data;
const contentType = res.headers['content-type'] || "application/pdf"; // 处理浏览器兼容
const blob = new Blob([content], {type: contentType});
if ('download' in document.createElement('a')) { //非ie -ie不支持预览
const href = URL.createObjectURL(blob);
open.location = href;
} else { //ie10+
navigator.msSaveBlob(blob, fileName);
}
})
} catch(err) {
}
}
留下足迹