Analysis of common methods used by JQuery to realize file download

This article describes the common methods of JQuery to achieve file download. Share with you for your reference, as follows:

GET method

1

window.location.href = url;

POST method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

var url = "下载接口地址";

// 构造隐藏的form表单

var $form = $("<form id='download' class='hidden' method='post'></form>");

$form.attr("url",url);

$(body).append($form);

// 添加提交参数

var $input1 = $("<input name='param1' type='text'></input>");

$input1.attr("value","参数值1");

$("#download").append($input1);

var $input2 = $("<input name='param2' type='text'></input>");

$input1.attr("value","参数值2");

$("#download").append($input2);

// 提交表单

$form.submit();

Why can't ajax download files

The data types returned by the server supported by ajax are: xml, json, script, html, and other types (such as binary streams) will be returned as Strings, which cannot trigger the browser's download processing mechanism and programs.

1

2

3

4

5

6

7

// ajax将返回数据转换为string,再利用该string创建Blob对象,下载的文件无法正确打开,数据可能已经被破坏

var blob = new Blob([data]);

//对于Blob对象,我们可以创建出一个URL来访问它。使用URL对象的createObjectURL方法。

var a = document.createElement('a');

a.download = 'data.doc';

a.href=window.URL.createObjectURL(blob);

a.click()

 

 

Ajax download file all code

function testAjaxDownload(){
	var url = "http://127.0.0.1:8080/candidateData/txtdownload";
	
	$.ajax({
		  type:'get',
		  url: url,
		  async:false,
		  success:function(data, statusTest, xhr){
			  	console.log(xhr);
			    console.log(xhr.getAllResponseHeaders());//获取所有的响应头消息
			    
			    let fileName = xhr.getResponseHeader("content-disposition").split(';')[1].split('=')[1].replace(/\"/g,'')
                let type =  xhr.getResponseHeader("content-type")
                let blob = new Blob([data],{type:type}) 
                
                //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                //IE10以上支持blob但是依然不支持download
                if ('download' in document.createElement('a')) { //支持a标签download的浏览器
                        const link = document.createElement('a')//创建a标签
                        link.download = fileName//a标签添加属性
                        link.style.display = 'none'
                        link.href = URL.createObjectURL(blob)
                        document.body.appendChild(link)
                        link.click()//执行下载
                        URL.revokeObjectURL(link.href) //释放url
                        document.body.removeChild(link)//释放标签
                } else { //其他浏览器
                        if(window.navigator.msSaveOrOpenBlob){
                                window.navigator.msSaveOrOpenBlob(blob,fileName)
                        }
                }
			    
		  }
	});
}

 Note: There is no problem with downloading text files in the above method, but there is a problem with downloading binary files such as excel and word files.

 

HTML5 Blob object

For a long time, JS has not had a better way to deal with binary directly. The existence of Blob allows us to directly manipulate binary data through JS. The Blob object can be seen as a container for storing binary data.

Create Blob object

1

var blob = new Blob(dataArr:Array<any>, opt:{type:string,endings:string});

  • dataArr: An array containing the data to be added to the Blob object. The data can be any number of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects.
  • opt: object, contains two attributes
    • type: used to set the attributes of the Blob object (such as: MIME type)
    • endings: (obsolete), set the endings parameter of the BlobBuilder.append() method, the value is "transparent" or "native"

1

2

3

4

// 例如创建一个装填DOMString对象的Blob对象

var data='<b style="font-size:32px;color:red;">Blob</b>'

var blob=new Blob([data],{ "type":"text/html"}); 

console.log(blob);

xmlhttprequest 2 + Blob to achieve file download

The xmlhttprequest 2 standard supports streaming files, used  xhr.responseas a return (not responseText)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

var url = "";

var xhr = new XMLHttpRequest();

xhr.open('GET', url, true);//get请求,请求地址,是否异步

xhr.responseType = "blob"// 返回类型blob

xhr.onload = function () { // 请求完成处理函数

 if (this.status === 200) {

 var blob = this.response;// 获取返回值

 var a = document.createElement('a');

 a.download = 'data.doc';

 a.href=window.URL.createObjectURL(blob);

 a.click();

  }

};

// 发送ajax请求

xhr.send();

 

Note: Use xmlhttprequest to specifyresponseTyp为blob,但是使用ajax是不能指定responseType为blob的

Guess you like

Origin blog.csdn.net/xiaokanfuchen86/article/details/113619482
Recommended