vue 下载文档乱码的解决

来自:网络
时间:2022-04-28
阅读:
目录

vue下载文档乱码

最近写功能 vue导出,但是不知道为啥,一请求接口就是乱码

vue 下载文档乱码的解决

后来在接口里写上了 这句话 responseType:“blob”,

vue 下载文档乱码的解决

vue 下载文档乱码的解决

能下载了赶快高兴打开一看 日,下载下来的文件里面又是乱码

vue 下载文档乱码的解决

后来不停的琢磨,咦终于找到方法了

vue 下载文档乱码的解决

这里面加了一句话 终于成功了!

vue 下载文档乱码的解决

我给大家把代码贴上

 exportAccountApi(data).then(res=>{
        console.log('777666',res)
        const blob = new Blob([res],{type: "application/vnd.ms-excel"});
        let fileName = "存款记录明细.xls";
         if ("download" in document.createElement("a")) {
           const elink  = document.createElement("a");
           elink.download =fileName;
           elink.style.display = "none";
           elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
           elink.click();
           URL.revokeObjectURL(elink.href);
           document.body.removeChild(elink);
         }else{
           navigator.msSaveBlob(blob.fileName)
         } 
      })

文件下载返回乱码处理 vue+axios

后端返回数据流是乱码,可以使用new Blob()这个方法处理,可以解决乱码问题。

乱码返回结果如下:

vue 下载文档乱码的解决

解决方法

    async postClick() {
      const res = await axios({
        url: '后端接口',
        method: 'post',
        data: { id: '文件id' }
        responseType: 'blob'
      })
      const content = res.data
      const fileName = 'a.png' // 文件名称
      // 如果不确定文件类型,type可以写空字符串
      const bolb = new Blob([content], { type: '' })
      if ('download' in document.createElement('a')) {
        const link = document.createElement('a')
        link.download = fileName
        link.style.display = 'none'
        // URL.createObjectURL(bolb) = blob:http://localhost:8080/a34a8a20-acf2-3f21-bc22-45994d9f0290
        link.href = URL.createObjectURL(bolb)
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
      }
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

返回顶部
顶部