歸納常見幾種下載文件方式

項目中常常會遇到下載文件(json、xml、excel、pdf、音頻、視頻)的需求,不同的下載方案能呈現不同的效果,歸納項目中常見幾種下載處理方案

一、直接使用 <a> 標籤

實現起來非常簡單,但是使用範圍侷限性強

<a> 標籤 只能發送get請求

  • href 屬性的值是 後端文件下載接口地址
  • download 屬性的值是下載後的文件名(html5 增加)
  • target="_black"在新頁面打開,避免當前頁閃屏

常見文件說明

  • excel文件直接使用<a>標籤href 即可下載,後臺返回文件名
  • json、img等文件會直接在瀏覽器打開,所以html5中增加 download屬性。(對 視頻、音頻不起作用)

實現代碼:

<a href="/getExcel?page=1" download="data.xsl" target="_black">點擊下載</a>

二、window.open、location.href實現

直接請求資源,瀏覽器會自動更具後綴名 保存或者展示文件,定義點擊調用方法即可

function downloadFile(url){
    window.open(url);
}
function downloadFile(url){
    location.href=url;
}

三、使用 iframe 下載

下載文件,無需打開新頁面同時頁面也不閃屏讓用戶無感,而且使用post請求,可以傳輸多個參數

定義下載方法

創建一個iframe和from的dom方法

function DownLoad(options) {

    var config = $.extend(true, { method: 'post' }, options);
    var $iframe = $('<iframe id="down-file-iframe" />');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
    $form.attr('action', config.url);
    for (var key in config.data) {
    $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
     }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

調用下載方法

function loginDown(){
	//定義參數
	var url = "localhost:8080/api/statistics/down.do";
	var data = {
		parentId:$("#parentId").val(),
		groupId:$("#groupId").val(),
		startTime:vue.startTime,
		endTime:vue.endTime
	} ;
	//調用下載方法
	DownLoad({ 
		url:url,data:data
	});
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章