前后端分离下载文件的几种方式

文章参考

http://blog.csdn.net/zhoumengshun/article/details/71405963

https://segmentfault.com/q/1010000011184241

在工作中遇到如下问题:

通过走网关下载一个文件,网关必须要带一个放在header请求头的token值,如果没有token就直接被拦截,请求不会到真正处理业务逻辑的service中

问题:

1、如果想要把token参数放到header中,只能使用ajax

2、如果使用ajax则只能获取返回来的只读数据,无法以文件方式写到硬盘中

解决办法:

把token做为参数放在URL问好后面中,例如:http://www.baidu.com?token=dsadfasfdsaf

下面四种方式是我总结前后端分离下载文件的方法

a. form表单下载文件

//表单方式直接下载文件
//url表示要下载的文件路径,如:htpp://127.0.0.1/test.rar
function downloadFile(url){
    var form=$("<form>");//定义form表单,通过表单发送请求
    form.attr("style","display:none");//设置为不显示
    form.attr("target","");
    form.attr("method","get");//设置请求类型  
    form.attr("action",url);//设置请求路径
    $("body").append(form);//添加表单到页面(body)中
    form.submit();//表单提交
}

b. iframe 下载文件

function downloadFile(url) {   
	try{ 
		var elemIF = document.createElement("iframe");   
		elemIF.src = url;   
		elemIF.style.display = "none";   
		document.body.appendChild(elemIF);   
	}catch(e){ 

	} 
}

c. 链接下载文件

<a href=”file.js”>file.js</a>

//该方法火狐有些版本是不支持的
window.location.href="htpp://www.baidu.com/test.rar"

//为了解决火狐有些版本不支持,可以改成这种方式
window.location="htpp://www.baidu.com/test.rar"; 

//该方法在火狐上没有效果的,在IE浏览器上是可以的
window.open("htpp://www.baidu.com/test.rar")

d. ajax 只能获取文本数据(如果是数据流已经转为了Blob,base64的格式)

function saveFile(url) {
  return new Promise(function(resolve, reject) {
    // Get file name from url.
    var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      resolve(xhr);
    };
    xhr.onerror = reject;
    xhr.open('GET', url);
    xhr.send();
  }).then(function(xhr) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
    a.download = filename; // Set the file name.
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    return xhr;
  });
}

备注:ajax请求的responseType="blob",这里是发送请求,返回的文件的数据

猜你喜欢

转载自hbiao68.iteye.com/blog/2397805