我正在尝试从我的网络服务下载文件。我需要将复杂的元数据传递给服务器以了解如何下载文件。以下是我能够在常绿浏览器中实现这一目标的方法:
// 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>
问题是我无法通过这样的对象。当然我可以放一个隐藏的输入并序列化它的值,但我的对象有点大,所以最终成为一个问题。
你如何解决这个问题?
答案 0 :(得分:0)
如果您只关注最近的浏览器,可以查看使用FileSaver.js。在IE10 +上运行时,它使用navigator.msSaveOrOpenBlob。
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();