返回文件流下载附件

down.js
/** * @url 下载地址 * @filename 所需要的文件名称 */ import { getToken } from '@/utils/auth' import { Message } from 'element-ui' export function downFile(url, pre = false) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() const urls = process.env.VUE_APP_BASE_API + url xhr.open('GET', urls, true) xhr.setRequestHeader('Content-Type', `application/json`) xhr.setRequestHeader('Authorization', `${getToken()}`) xhr.responseType = 'blob' xhr.onload = () => { if (xhr.status === 200) { if (xhr.getResponseHeader('content-disposition') == null) { // 说明文件不存在 Message({ message: '导出失败', type: 'error', duration: 5 * 1000 }) reject(new Error('导出失败')) } const fileName = decodeURIComponent(xhr.getResponseHeader('content-disposition').split('fileName=')[1]) if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(xhr.response, fileName) } else { const body = document.querySelector('body') const imgurl = window.URL.createObjectURL(xhr.response) if (!pre) { const link = document.createElement('a') link.download = fileName link.href = imgurl link.style.display = 'none' body.appendChild(link) link.click() body.removeChild(link) window.URL.revokeObjectURL(link.href) Message({ message: '下载成功!', type: 'success', duration: 5 * 1000 }) resolve({ data: '', msg: '下载成功!', state: xhr.statusText }) } else { resolve({ data: imgurl, msg: '获取成功', state: xhr.statusText }) } } } else { Message({ message: xhr.statusText, type: 'error', duration: 5 * 1000 }) reject(new Error(xhr.statusText)) } } xhr.send() }) }

 api.js

export function checkExcel(id) {
  return downFile(
    `/project/bid/checkExcel?id=${id}`
  )
}

 //返回url

    static downloadWithUrl(url: string) {
        const downloadUrl = this.getHost() + url;
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.location.href = downloadUrl;
        } else {
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = downloadUrl;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }

 

posted @ 2021-11-04 13:59  闰土的土  阅读(137)  评论(0编辑  收藏  举报