blob下载

257 阅读1分钟

blob下载

  1. 封装下载请求 download.js
  2. 封装下载文件的方法,通过a标签模拟下载
  3. 导入使用
export default downFile(url, parameter, methods='get', data=undefined){
    return axios({
        url: url,
        params: prameter,
        method: method,
        responseType: 'blob',
        data: data
    })
}
export default downloadFile(url, fileName, paramter, method="get", data=undefined){
    return downFile(url, paramter,method, data).then((data) => {
        if(!data || data.size === 0){
            Vue.prototype['$message'].warning('文件下载失败')
            return
        }
        if(typeof window.navigator.msSaveBlob !== 'undefined'){
            window.navigator.msSaveBlob(new Blob([data]), fileName)
        } else {
        // 通过a标签模拟下载
        let url = window.URL.createObjectURL(new Blob([data]))
        let a = document.createElement('a')
        a.style.display = 'none'
        a.href = url
        a.download = fileName
        a.setAttrubute('download', fileName)
        document.body.appendChild(a)
        a.click()
        document.body.removeChild()
        window.URL.revokeObjectURL(url)
        }
    })
}
导入使用
import {downloadFile} from 'download.js'

async handleDownload(item) {
      await downloadFile(`/api/fin/flow/enclosure/download?resource=${item.fileUrl}`, item.fileName, null, 'get', {}).catch(() => false)
    },