问题描述:项目中使用的是vue框架进行开发,因为文件下载存在权限问题,所以并不能通过 a 链接的 href 属性直接赋值 URL进行下载,

(如果你的文件没有下载权限,可以直接通过href属性赋值URL的方法进行文件下载),所以使用vue-resource请求文件流后,借助Blob对象实现下载,

但是仍然存在解压的问题(针对压缩文件),而 docx等文档格式主要出现的就是乱码问题。

问题截图

这个出现以上解压问题的代码,通过vue-resource进行请求文件资源

downloadFile(attachment) {
        let fileName = attachment.displayName;
        this.$http.get(strategyDownloadUrl + '/' + attachment.id).then((res) => {
          if(typeof(res.data) == 'string'){
            var blob = new Blob([res.data], {type:'application/octet-stream'})
            if (window.navigator.msSaveOrOpenBlob) {//msSaveOrOpenBlob方法返回bool值
              navigator.msSaveBlob(blob, fileName);//本地保存
            } else {
              var link = document.createElement('a');//a标签下载
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              window.URL.revokeObjectURL(link.href);
            }
          }else{
            swal(res.data.msg,'','info')//个人弹窗忽视
          }
        })
      },

采用原生对象XHRHttpRequest进行文件请求(也可通过jquery的ajax进行文件请求),可以正常解压文件,图就不贴了

downloadFile(attachment) {
        let that = this
        var ajax = new XMLHttpRequest()
        ajax.responseType = 'blob'
        ajax.open("GET",strategyDownloadUrl + '/' + attachment.id,true)
        ajax.setRequestHeader('X-Authorization','Bearer ' + this.$store.state.token)
        ajax.onreadystatechange = function(){
          if(this.readyState == 4) {
            if(this.status == 200) {
              //console.log(this.response) // should be a blob
              that.downloadHandler(this.response,attachment.displayName)
            } else if(this.responseText != "") {
              //console.log(this.responseText);
            }
          } else if(this.readyState == 2) {
            if(this.status == 200) {
              this.responseType = "blob"
            } else {
              this.responseType = "text"
            }
          }
        };
        ajax.send(null);
      }

如有不正确的地方,请指正交流,共同进步。

版权声明:本文为note-blog原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:http://www.cnblogs.com/note-blog/p/8065199.html