js下载文件到本地的各种方法总结

1.此方法火狐有些版本是不支持的

window.location.href = 'https://*****.oss-cn-**.aliyuncs.com/*********';

2.为了解决火狐有些版本不支持,可以改成这种方式

window.location='https://*****.oss-cn-**.aliyuncs.com/*********';

3.该方法IE和火狐都可以,url表示要下载的文件路径

function(url){
    try {
          var elemIF = document.createElement("iframe");
          elemIF.src = url;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        } catch (e) {
          alert("下载异常!");
        }
}

4.form表单的形式


downloadFile(url){
      var form=$("
"); form.attr("style","display:none"); form.attr("target",""); form.attr("method","get"); form.attr("action",url); $("body").append(form); form.submit();//表单提交} }

5.a标签的方式 , 修复firefox中无法触发click

function(url,name){
    var a = document.createElement("a");
     a.download = name + ".xls";
     a.href = url;
     $("body").append(a); // 修复firefox中无法触发click
     a.click();
     $(a).remove();
}

6.假如后台给的文件流


function (formData, url, name) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true); // 也可以使用POST方式,根据接口
    xhr.responseType = "blob"; // 返回类型blob
    // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
      // 请求完成
      if (this.status === 200) {
        // 返回200
        var blob = this.response;
        var reader = new FileReader();
        reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
        reader.onload = function (e) {
          // 转换完成,创建一个a标签用于下载
          var a = document.createElement("a");
          a.download = name + ".xls";
          a.href = e.target.result;
          $("body").append(a); // 修复firefox中无法触发click
          a.click();
          resolve(200)
          $(a).remove();
        };
      }
    };
    // 发送ajax请求
    xhr.send(formData);
  })
}

7.download.js 我粘贴一下download的源码

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.download = factory();
  }
}(this, function () {
 
    return function download(data, strFileName, strMimeType) {
 
        var self = window, // this script is only for browsers anyway...
            defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
            mimeType = strMimeType || defaultMime,
            payload = data,
            url = !strFileName && !strMimeType && payload,
            anchor = document.createElement("a"),
            toString = function(a){return String(a);},
            myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
            fileName = strFileName || "download",
            blob,
            reader;
            myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
      
        if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
            payload=[payload, mimeType];
            mimeType=payload[0];
            payload=payload[1];
        }
 
 
        if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
            fileName = url.split("/").pop().split("?")[0];
            anchor.href = url; // assign href prop to temp anchor
              if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
                var ajax=new XMLHttpRequest();
                ajax.open( "GET", url, true);
                ajax.responseType = 'blob';
                ajax.onload= function(e){ 
                  download(e.target.response, fileName, defaultMime);
                };
                setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
                return ajax;
            } // end if valid url?
        } // end if url?
 
 
        //go ahead and download dataURLs right away
        if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
        
            if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
                payload=dataUrlToBlob(payload);
                mimeType=payload.type || defaultMime;
            }else{            
                return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
                    navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
                    saver(payload) ; // everyone else can save dataURLs un-processed
            }
            
        }//end if dataURL passed?
 
        blob = payload instanceof myBlob ?
            payload :
            new myBlob([payload], {type: mimeType}) ;
 
 
        function dataUrlToBlob(strUrl) {
            var parts= strUrl.split(/[:;,]/),
            type= parts[1],
            decoder= parts[2] == "base64" ? atob : decodeURIComponent,
            binData= decoder( parts.pop() ),
            mx= binData.length,
            i= 0,
            uiArr= new Uint8Array(mx);
 
            for(i;i

重点 设置响应头 responseType:'blob'

this.$axios.post("/api/xxx/xxx/xxx",this.$qs.stringify({range:0,}),{responseType:'blob'}).then(msg=>{
                console.log(msg.data) //打印出来是blob对象,已经不是乱码了
                let url = window.URL.createObjectURL(msg.data); //表示一个指定的file对象或Blob对象
                console.log(url,"看一下这是啥")
                let a = document.createElement("a"); 
                document.body.appendChild(a);
                let fileName=msg.headers["content-disposition"].split(";")[1].split("=")[1];  //filename名称截取
                a.href = url;
                a.download = fileName; //命名下载名称
                a.click(); //点击触发下载  
                window.URL.revokeObjectURL(url);  //下载完成进行释放
        })

重点是 设置响应头 responseType:"arraybuffer"

  this.$axios({
        method: "get",
        url:"xxx/api/xxx/xxx",
        headers:{
            "Content-Type": "application/json"
        },
        responseType:"arraybuffer"
    }).then(res=>{
        let headers = res.headers
        let blob = new Blob([res.data],{
            type: headers["Content-type"]
        })
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = 'XXX.xlsx'
        link.click()
        document.body.removeChild(link);
    })

你可能感兴趣的:(js下载文件到本地的各种方法总结)