封装fetch(post请求)下载文件的方法

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)
    });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值