Several methods of javascript to achieve download

In the process of project development, we often encounter the download function; based on the method I have used, I made a summary, and then wrote this article as a record!

First, the use of a label (get request)
a tag is the easiest way, only need to address files or an interface to a href attribute tags may be added as a tag to download attribute specifies the name of the downloaded file; download attribute can be omitted If omitted, the browser will automatically recognize the source file name.

<a href="文件地址" download='文件名'>下载</a>
 
//url 文件地址 或 接口地址
function downLoadFile(url) {
    
    
    let a = document.createElement('a')
    a.href = url;
    a.download = '文件名'
    a.click();
} 

Advantages:
1. When the file is txt, png, jpg and other browsers that support opening files, they will not download but open the file directly. At this time, add the download attribute to download;
Disadvantages:
1. You need to know the download address;
2 , Cannot download files that can be browsed by browsers under cross-domain;
3. Cannot perform authentication;

Two, window.open() method (get request)

//url 文件地址 或 接口地址
function downLoadFile() {
    
    
	let url = '/xxx/xxx'; //接口
    window.location.href = url;
} 

Advantages:
1. Simple and straightforward;
Disadvantages:
1. Unable to know the download progress;
2. URL length limitation and encoding problems will occur;
3. No header can be added, and authentication cannot be performed;
4. The files are txt, png, jpg When these browsers support opening files, they will not be downloaded, but will be opened directly;

3. A form form is
dynamically generated through the form submission method (get request) , and the form submission function is used to realize the download

//url 文件地址 或 接口地址
//data 请求参数:[{key:name,key1:value}]
function downLoadFile(url,data){
    
    
	let form = document.createElement('form');
	for(let i in data){
    
    
		let input = document.createElement('input');
		input.name = data[i].key;
		input.value = data[i].key1;
		form.appendChild(input)
	}
	form.style.display = 'none';
	form.method = "GET";//请求方式
	form.action = 'url'//下载文件地址
	document.body.appendChild(form);
	form.submit();
	document.body.removeChild(form);
}

Advantages:
1. Traditional method, good compatibility, no URL length limitation problem;
Disadvantages:
1. Unable to know the download progress;
2. When the file is txt, png, jpg and other browsers that support opening files, it won’t Download but open the file directly;

4.
Generate an iframe dynamically through iframe (get request, address splicing parameters) , using iframe has a src attribute, its essence is to send http request

//url 文件地址 或 接口地址
//id 参数id
function downLoadFile(){
    
    
	let iframe= document.createElement('iframe');
	iframe.src = `${
    
    item.url}?id=${
    
    id}`;
	iframe.style.display = 'none'
	document.body.appendChild(iframe);
}

Disadvantages:
1. Compatibility issues;
2. When the files are txt, png, jpg and other browsers that support opening files, they will not download but directly open the file;

5. Use the blob format with the a tag (post request) to
convert the file into a Blob binary object, and then download it with the a tag.

return new Promise((resolve, reject) => {
    
    
    this.$http.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    this.$http({
    
    
      method: 'post',
      url: '/xxx/xxx', // 接口地址
      data: data, // 参数
      responseType: 'blob' // 表明返回服务器返回的数据类型
    }).then(response => {
    
    
      	if(response.headers.filename != undefined){
    
    
      		resolve(response.data)
	        let blob = new Blob([response.data], {
    
    
	          type: 'application/vnd.ms-excel'
	        })
	        let fileName = Date.parse(new Date()) + '.xlsx'
	        if (window.navigator.msSaveOrOpenBlob) {
    
    
	          navigator.msSaveBlob(blob, fileName)
	        } else {
    
    
	          var link = document.createElement('a')
	          link.href = window.URL.createObjectURL(blob)
	          link.download = fileName
	          let evt = document.createEvent('MouseEvents')
	          evt.initEvent('click',true,true)
	          link.dispatchEvent(evt)
	          //释放内存
	          window.URL.revokeObjectURL(link.href)
	        }
      	}else{
    
    
      		this.$message.error("数据为空!")
      	}
      },
      err => {
    
    
        reject(err)
      }
    )
})

Advantages:
1. Header can be set, and authentication can also be added;
2. Files that can be browsed by the browser can be downloaded directly;
Disadvantages:
1. Not available under IE10;

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/112007458