在实际项目中,经常会实现文件下载的功能,以下代码基本实现了下载功能的处理,其中包括如果文件不存在获取其他的错误时,接口返回的不是文件数据,而是错误提示的处理。

        比如:当下载接口以get或者post请求时,返回的Blob中数据的type一般是文件的类型,如下图:

如果返回的是错误的提示则返回的Blob数据中type是‘application/json’,如下图:

     首先定义下载的接口,然后在页面中调用该接口并处理数据。注意返回json数据的特殊处理。

export function downData (params) {
    return http({
        url: 'xxx', // 下载文件的接口地址
        method: 'get',
        params: params,
        responseType:'blob'
    })
}
    // 下载文件的接口
    downData(option).then(res=>{
              if (!res) {
                  return
              }
              // 无法导出时,报错的问题的处理
              if (res.type == "application/json") {
                const reader = new FileReader(); 
                reader.readAsText(res, "utf-8");
                reader.onload = function () {
                const msg = JSON.parse(reader.result);
                 
                 this.$notification["error"]({
                    message: "提示",
                    description:msg,
                    duration: 4,
                  });
                  }
                  return 
              }
              // 以下载xls文件为例
               let fileName='xxxx'
               let suffix='xls'

                  let url = window.URL.createObjectURL(new Blob([res]))
                  let link = document.createElement('a')
                  link.style.display = 'none' 
                  link.href = url
                  link.setAttribute('download', fileName+"."+suffix)
                  document.body.appendChild(link)
                  link.click()
                  document.body.removeChild(link) 
                  window.URL.revokeObjectURL(url)
              
           })

        以上代码基本可以实现项目中关于文件下载的要求。

Logo

前往低代码交流专区

更多推荐