【发布时间】:2020-02-06 21:39:31
【问题描述】:
我有一个可以下载的事件处理程序,它在除 IE 之外的所有浏览器上都运行良好,所以我用msSaveBlob 处理它并下载文件,但是当我打开它时,它说格式不好,所以我的猜测是我没有在 blob 中使用有效数据。
$(document).on('click', '.register-file-uploader-download-file', function () {
let $fileResultsItem = $(this).closest('.form-fields__file-results-item');
const fileName = $fileResultsItem.find('.multiple-files-upload-item').data('filename');
const fileUrl = $fileResultsItem.find('.multiple-files-upload-item').val();
if (fileUrl.length > 0) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var url = window.URL || window.webkitURL;
let blobFileUrl = url.createObjectURL(this.response);
if (window.navigator && navigator.msSaveBlob) { // For IE
const blobObj = new Blob([this.response], { type: 'application/octet-stream' });
return navigator.msSaveBlob(blobObj, fileName);
}
const a = document.createElement('a');
a.style.display = 'none';
a.href = blobFileUrl;
a.download = `${fileName}`;
document.body.appendChild(a);
a.click();
url.revokeObjectURL(blobFileUrl);
}
};
xhr.open('GET', fileUrl);
xhr.responseType = 'blob';
xhr.send();
}
});
【问题讨论】:
-
您要下载什么文件格式?这篇文章有帮助吗? github.com/angular-ui/ui-grid/issues/2312#issuecomment-66465065 我可以提供一个解决方案,但它只考虑了 CSV 文件。
-
@Max 这是通用控件,在这种情况下,我使用的是图像,但应该实现使用所有格式
-
对不起,我帮不上什么忙。也许这个答案很有用,如果没有,恐怕我无法提供任何其他建议。 stackoverflow.com/questions/24007073/…
标签: javascript jquery download blob