我正在尝试从我的web服务下载文件。我需要将复杂的元数据传递给服务器,以便知道如何下载文件。下面是我如何在常青树浏览器中做到这一点:
// 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>问题是我不能传递这样的对象。当然,我可以放置一个隐藏的输入并序列化它的值,但是我的对象有点大,所以这最终会成为一个问题。
你怎么解决这个问题呢?
发布于 2014-12-05 04:02:32
如果您只关心最近的浏览器,那么可以考虑使用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();https://stackoverflow.com/questions/27276409
复制相似问题