JavaScript – Download File 下載檔案

let url = "your_file_path";
let filename = url.split("/").pop();
var req = new XMLHttpRequest();
req.open("POST", url, true);
//監聽進度事件
req.addEventListener("progress", function(evt){
  if(evt.lengthComputable){
      console.log(evt.loaded);
      console.log(evt.total);
  }
},false);

req.responseType = "blob";
req.onreadystatechange = function(){
    if(req.readyState === 4 && req.status === 200){
       if(typeof window.chrome !== 'undefined'){
           //chrome version
           var link = document.createElement('a');
           link.href = window.URL.createObjectURL(req.response);
           link.download = filename;
           link.click();
       } else if(typeof window.navigator.msSaveBlob !== 'undefined'){
           //IE version
           var blob = new Blob([req.response], { type: 'application  force - download' });
           window.navigator.msSaveBlob(blob, filename);
       }else{
           //Firefox version
           var file = new File([req.response], filename, { type: 'application / force - download'});
           window.open(URL.createObjectURL(file));
       }

       console.log("downloaded!");
    }
};
req.send();

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部