我正在尝试从我的网络服务下载文件。我需要将复杂的元数据传递到服务器才能知道如何下载文件。以下是我如何在常青浏览器中实现这一目标:
// i use angular but not important for this demo
$http.post({ /* complex object */ }).then(xhr){
// use download attribute
// http://davidwalsh.name/download-attribute
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(xhr.data);
hiddenElement.target = '_blank';
hiddenElement.download = $scope.filename + '.csv';
hiddenElement.click();
hiddenElement.remove();
});
当然,我无法发布 IE 上的下载属性。我之前使用过的解决方法是:
$("body>#download_iFrame").remove();
$("body").append('<iframe name="downloadFrame" id="download_iFrame" style="display:none;" src="" />');
$("#form-download")[0].submit();
然后在html中
<form target="downloadFrame"
action="'api/search/export/'"
id="form-download"></form>
问题是我无法传递这样的对象。当然,我可以放置一个隐藏输入并序列化其值,但我的对象有点大,所以这最终成为一个问题。
您如何解决这个问题?
如果您只关心最近的浏览器,您可以考虑使用文件保存器.js https://github.com/eligrey/FileSaver.js。当在 IE10+ 上运行时,它使用navigator.msSaveOrOpenBlob http://msdn.microsoft.com/en-us/library/ie/hh772332(v=vs.85).aspx.
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = fuction (eventInfo) {
if (this.status == 200) {
var blob = this.response;
// FileSaver.js usage:
saveAs(blob, "filename.ext");
// Or IE10+ specific:
navigator.msSaveOrOpenBlob(blob, "filename.ext");
}
};
xhr.send();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)