JS端基於download.js實現圖片、視訊時直接下載而不是開啟預覽

佚名發表於2020-05-18

專案中的附件列表,通常情況都需要提供下載、刪除的功能,功能本身沒有什麼要說的,都是基本功能,使用瀏覽器的的下載功能,也都是用window.open(url),或者window.location.href=url的方式,url即為附件下載介面,瀏覽器自動解析,如果是圖片、視訊、txt等格式的會直接預覽檔案,而不是像docx、xlsx一樣直接下載,專案中為了功能明確,將預覽單獨加了一個檢視按鈕,下載按鈕要實現無論什麼檔案格式都直接下載。

有兩種方式處理:

一.後臺介面層面處理:(比較常見)

響應頭中新增標識:
Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode(annotation.FileName, System.Text.Encoding.UTF8));

新增後,瀏覽器就會全都直接下載,不區分檔案格式

二.前端JS使用XMLHttpRequest結合download.js處理

1)首先頁面中需要引用download.js

download官方:http://danml.com/download.html

http://danml.com/js/download2.js

2)公共方法

/*
    * 使用download.js 強制瀏覽器下載圖片、視訊等檔案
    * @param {any} url url連結地址
    * @param {any} strFileName 檔名
    * @param {any} strMimeType 檔案型別
    * dzl
    * 2020年5月8日
     */
    function downloadfile(url, strFileName, strMimeType) {
      var xmlHttp = null;
      if (window.ActiveXObject) {
        // IE6, IE5 瀏覽器執行程式碼
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } else if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行程式碼
        xmlHttp = new XMLHttpRequest();
      }
      //2.如果例項化成功,就呼叫open()方法:
      if (xmlHttp != null) {
        xmlHttp.open("get", url, true);
        xmlHttp.responseType = 'blob';//關鍵
        xmlHttp.send();
        xmlHttp.onreadystatechange = doResult; //設定回撥函式
      }
      function doResult() {
        if (xmlHttp.readyState == 4) { //4表示執行完成
          if (xmlHttp.status == 200) { //200表示執行成功
            download(xmlHttp.response, strFileName, strMimeType);
          }
        }
      }
    }

注意: xmlHttp.responseType = 'blob';是關鍵,必須要設定

3)下載按鈕點選事件中呼叫公共方法

downloadfile(url, filename, getFileType(filename))

附上根據檔名的尾綴 返回檔案型別的公共方法:

/*
 * 根據檔名的尾綴 返回檔案型別
 * @param {any} fileName 檔名
 * dzl
 * 2020年5月9日
 */
function getFileType(fileName) {
  // 字尾獲取
  let suffix = '';
  // 獲取型別結果
  let result = '';
  try {
    const flieArr = fileName.split('.');
    suffix = flieArr[flieArr.length - 1];
  } catch (err) {
    suffix = '';
  }
  // fileName無字尾返回 false
  if (!suffix) { return false; }
  suffix = suffix.toLocaleLowerCase();
  // 圖片格式
  const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
  // 進行圖片匹配
  result = imglist.find(item => item === suffix);
  if (result) {
    return 'image';
  }
  // 匹配txt
  const txtlist = ['txt'];
  result = txtlist.find(item => item === suffix);
  if (result) {
    return 'txt';
  }
  // 匹配 excel
  const excelist = ['xls', 'xlsx'];
  result = excelist.find(item => item === suffix);
  if (result) {
    return 'excel';
  }
  // 匹配 word
  const wordlist = ['doc', 'docx'];
  result = wordlist.find(item => item === suffix);
  if (result) {
    return 'word';
  }
  // 匹配 pdf
  const pdflist = ['pdf'];
  result = pdflist.find(item => item === suffix);
  if (result) {
    return 'pdf';
  }
  // 匹配 ppt
  const pptlist = ['ppt', 'pptx'];
  result = pptlist.find(item => item === suffix);
  if (result) {
    return 'ppt';
  }
  // 匹配 視訊
  const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
  result = videolist.find(item => item === suffix);
  if (result) {
    return 'video';
  }
  // 匹配 音訊
  const radiolist = ['mp3', 'wav', 'wmv'];
  result = radiolist.find(item => item === suffix);
  if (result) {
    return 'radio';
  }
  // 其他 檔案型別
  return 'other';
}

download.js原始碼

//download.js v4.21, by dandavis; 2008-2018. [MIT] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// https://github.com/rndme/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
            }
             
        }else{//not data url, is it a string with special needs?
            if(/([\x80-\xff])/.test(payload)){           
                var i=0, tempUiArr= new Uint8Array(payload.length), mx=tempUiArr.length;
                for(i;i<mx;++i) tempUiArr[i]= payload.charCodeAt(i);
                payload=new myBlob([tempUiArr], {type: mimeType});
            }        
        }
        blob = payload instanceof myBlob ?
            payload :
            new myBlob([payload], {type: mimeType}) ;
 
 
        function dataUrlToBlob(strUrl) {
            var parts= strUrl.split(/[:;,]/),
            type= parts[1],
            indexDecoder = strUrl.indexOf("charset")>0 ? 3: 2,
            decoder= parts[indexDecoder] == "base64" ? atob : decodeURIComponent,
            binData= decoder( parts.pop() ),
            mx= binData.length,
            i= 0,
            uiArr= new Uint8Array(mx);
 
            for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
 
            return new myBlob([uiArr], {type: type});
         }
 
        function saver(url, winMode){
 
            if ('download' in anchor) { //html5 A[download]
                anchor.href = url;
                anchor.setAttribute("download", fileName);
                anchor.className = "download-js-link";
                anchor.innerHTML = "downloading...";
                anchor.style.display = "none";
                anchor.addEventListener('click', function(e) {
                    e.stopPropagation();
                    this.removeEventListener('click', arguments.callee);
                });
                document.body.appendChild(anchor);
                setTimeout(function() {
                    anchor.click();
                    document.body.removeChild(anchor);
                    if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
                }, 66);
                return true;
            }
 
            // handle non-a[download] safari as best we can:
            if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
                if(/^data:/.test(url))  url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
                if(!window.open(url)){ // popup blocked, offer direct download:
                    if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
                }
                return true;
            }
 
            //do iframe dataURL download (old ch+FF):
            var f = document.createElement("iframe");
            document.body.appendChild(f);
 
            if(!winMode && /^data:/.test(url)){ // force a mime that will download:
                url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
            }
            f.src=url;
            setTimeout(function(){ document.body.removeChild(f); }, 333);
 
        }//end saver
 
 
 
 
        if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
            return navigator.msSaveBlob(blob, fileName);
        }
 
        if(self.URL){ // simple fast and modern way using Blob and URL:
            saver(self.URL.createObjectURL(blob), true);
        }else{
            // handle non-Blob()+non-URL browsers:
            if(typeof blob === "string" || blob.constructor===toString ){
                try{
                    return saver( "data:" + mimeType  + ";base64," + self.btoa(blob) );
                }catch(y){
                    return saver( "data:" + mimeType  + "," + encodeURIComponent(blob) );
                }
            }
 
            // Blob but not URL support:
            reader=new FileReader();
            reader.onload=function(e){
                saver(this.result);
            };
            reader.readAsDataURL(blob);
        }
        return true;
    }; /* end download() */
}));

在前端想要生成txt或者其他格式檔案來儲存一些資料,或者在資料請求伺服器成功後想要將資料生成檔案並下載,這些需求還是比較多的,這裡使用到的download.js。既可以滿足這些需求。js檔案下載外掛介紹和使用方法 download.js

第一步:下載

1.下載可以在官網上進行下載 原網址:download2.js

2.也可以使用我上傳的資源(下載與上述官網) 免費哦! 下載

第二步:引用

1.將下載的檔案放在專案中,並使用 <script src="./download2.js"></script> 進行引用 (速度快)

2.使用網路引用 <script src="http://danml.com/js/download2.js"></script>

第三步:開始使用

//生成一個txt的檔案,講字串變數 str 的內容放在裡面,並完成下載
var str = "hello world可以中文嗎?答案:可以的";
download(str, "Text.txt", "text/plain");
 
//也將生成一個txt檔案,和上面的結果是一摸一樣
str = "data:text/plain,hello%20world";
download(str, "dlDataUrlText.txt", "text/plain");
 
//將陣列或者json物件寫入到檔案中
var debug = {hello : "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)]);
download(blob, "dlTextBlob.txt", "text/plain");
 
var str= "hello world", arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
  arr[b]=a.charCodeAt();
});
download( arr, "textUInt8Array.txt", "text/plain" );
 
//將html頁面中的一部分生成單獨的 html文件
download(document.body.outerHTML, "dlHTML.html", "text/html");
 
//給字串新增標籤,或者html片段直接給方法,將會生成對應內容的檔案
download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");
 
 //將ajax查詢回來的結果,賦值給檔案,並下載
$.ajax({
  url: "/download.html",
  success: download.bind(true, "text/html", "dlAjaxCallback.html")
});
 
//將圖片的base64裝入到圖片中並下載。
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
 
//使用xhr獲取本域名下檔案,並封裝到檔案進行下載。這裡的前提是xhr訪問的檔案必須和該程式執行在同一域名下,
//否則會報跨域的問題。比如此程式執行在localhost下面,而這裡的訪問地址使用的是http://danml.com,就會訪問不成功。
  var x=new XMLHttpRequest();
  x.open("GET", "http://danml.com/wave2.gif", true);
  x.responseType = 'blob';
  x.οnlοad=function(e){
    download(x.response, "dlBinAjax.gif", "image/gif" );
  };
  x.send();

擴充套件:還可以使用檔案上傳再下載進行測試。

<input id="file" type="file" οnchange="download(this.files[0], this.files[0].name, this.files[0].type)">

以上就是JS端基於download.js實現圖片、視訊時直接下載而不是開啟預覽的詳細內容,

相關文章