簡體   English   中英

保存通過 REST API 在 Internet Explorer 下載參數上獲取的虛擬文件不起作用

[英]Save virtual file get by REST API on Internet Explorer download parameter doesn't work

我有這段代碼可以在除 IE 之外的大多數瀏覽器上正常工作:

<a href="http://xxx.xxx.xxx.xxx/presets/current" download="configuration.bin">
    Save
</a>

問題是下載參數在 IE 上不起作用。

為了糾正它,我試過這段代碼

var request = new XMLHttpRequest();
request.open('GET', "http://xxx.xxx.xxx.xxx/presets/current", true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        var blob = new Blob( [e.target.result] );
        navigator.msSaveBlob( blob, 'configuration.bin' );
        };
    };
request.send();

AngularJS 上,我也嘗試過使用 $http 這樣的代碼:

$http({method: 'GET', url: "http://xxx.xxx.xxx.xxx/presets/current"})
    .success(function(data, status, headers, config) {
        var blob = new Blob([data]);
        navigator.msSaveBlob( blob, 'configuration.bin' );
    })

問題是Chrome上下載的文件大小是134K,IE上用這個代碼下載的文件是180K

問題:我怎樣才能完全按照我得到的文件保存文件?

在IE中只能使用msSaveBlob下載文件,需要根據需要正確設置blob類型。 跨瀏覽器的方法應該是這樣的:

//change to the type you need
var blob = new Blob([byteArray], { type: 'application/pdf' });
//output file name
var fileName = "test.pdf";

//detect whether the browser is IE/Edge or another browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  //To IE or Edge browser, using msSaveorOpenBlob method to download file.
  window.navigator.msSaveBlob(blob, fileName);
} else {
    //To another browser, create a tag to downlad file.
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = fileName;
    a.click();    
    window.URL.revokeObjectURL(url);
    a.remove();
}

我用這種方法下載文件,在IE和Chrome下大小是一樣的。 您還可以參考這些類似的線程: link1link2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM