why
采用get方法时较为简单,但是涉及到传参较多时,要求我封装一个采用post下载文件的方法
how
原生方法实现
//触发方法下载后
const params = [new Date(),new Date(),new Date(),new Date()];
var url = 'http://localhost:8080/api/file';
fetch(url
,
{
method: 'POST',
body: window.JSON.stringify(params),
credentials: 'include',
headers: new Headers({
'Content-Type': 'application/json',
})
}
).then(res => res.blob().then(blob => {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = res.headers.get('Content-Disposition');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
document.getElementById('status').innerHTML = '下载完成';
}))
代码如下
import 'whatwg-fetch'
import 'es6-promise'
import { Cookies } from 'utils-fy'
import {Context} from '../util/globalVariable'
/**type:post或put
* url:链接
* paramsObj:请求的参数
* cb:回掉函数
* */
// 下载成功则无返回值,下载失败则会报错,文件名约定接收后端定得名,已处理跨域问题
// 使用方法:
// export function downfile(data, successFn, failFn) {
// postfile("post",`/api/file`,data, successFn, failFn);
// }
export function postfile(type, url, paramsObj, successFn, failFn, timeout) {
const token = Cookies.getCookie("token");
Promise.race([
fetch(`/${Context}/` + url, {
method: type,
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
"Authorization": "Bearer " + token
},
body: JSON.stringify(paramsObj)
}),
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('timeout')), timeout || 2 * 60 * 1000);//意味着30秒超时
setTimeout(() => reject(new Error('timeout')), timeout || 2*60 * 1000);//意味着30秒超时
})
]).then(res => {
if (res.status != 200) {
console.log(`res请求报错---${url}:`, res);
failFn && failFn(res)
} else {
res.blob().then(blob => {
//模拟a链接得原理下载该文件,无返回值(res)
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = res.headers.get('Content-Disposition');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
})
successFn && successFn(res)
}
}).catch(ex => {
/*请求超时的处理*/
console.log("ex:", ex);
failFn && failFn(ex)
});
}