js使用Blob對象下載兼容ie


官方解釋:Blob是一個類文件的不可變的原始數據對象,非javascript原生數據類型,File對象就是繼承自Blob對象,且在Blob的基礎上進行擴展,以便支持用戶系統上的文件。

先貼下載代碼

    var html =
        '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>' +
        document.getElementsByClassName("projectTable")[0].outerHTML +
        "</body></html>";
      var blob = new Blob([html], { type: "application/vnd.ms-excel" });
    var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "工程統計表.xls"; document.body.appendChild(a); a.onclick = function() { document.body.removeChild(a); }; a.click();

如果直接使用Blob下載,其他瀏覽器正常但在ie會出現這樣的問題無法正常下載

 

 百度發現:微軟在ie10 和ie11中有兩個能解決這個問題的方法:window.navigator.msSaveBlobwindow.navigator.msSaveOrOpenBlob 方法,這兩個方法的區別在於,The Navigator.msSaveOrOpenBlob() method saves the File or Blob to disk. This method behaves in the same way as Navigator.msSaveBlob() except that this enables the file open option.(前者只有保存,后者有保存和打開兩個選項)

msSaveOrOpenBlob 官方解釋:Launches the associated application for a File or Blob.(啟動File或Blob的關聯應用程序)

 解決方法:

    var html =
        '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>' +
        document.getElementsByClassName("projectTable")[0].outerHTML +
        "</body></html>";
      var blob = new Blob([html], { type: "application/vnd.ms-excel" });
      //判斷ie
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, "工程統計表.xls");
      } else {
        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "工程統計表.xls";
        document.body.appendChild(a);
        a.onclick = function() {
          document.body.removeChild(a);
        };
        a.click();
      }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM