axios请求文件下载

2019-07-11  本文已影响0人  放任自由f0
请求下载文件
axios({
        method: 'GET',
        url: '/api',
        params: params,
        responseType: 'blob'
      }).then(res=>{
        let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
        let url = window.URL.createObjectURL(blob);
        window.location.href = url;
      }).catch(err=>{
        console.log(err)
      })

 { type: 'application/pdf' }

axios.post('/api',{
    // 传参
},
{
    responseType:'blob'    // 设置响应数据类型
})
.then(res=>{
    if (res.status == 200) {
        let url = window.URL.createObjectURL(new Blob([res.data]))
        let link= document.createElement('a')
        link.style.display='none'
        link.href=url
        link.setAttribute('download', fileName)    // 自定义下载文件名(如exemple.txt)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    }


上一篇 下一篇

猜你喜欢

热点阅读