我有此代码可在大多数浏览器上正常工作,但IE除外:
<a href="http://xxx.xxx.xxx.xxx/presets/current" download="configuration.bin">
Save
</a>
问题是download参数在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中大小相同。