首页 > 解决方案 > 使用 JavaScript 保存 blob 始终会保存一个空文件

问题描述

以下代码中最有趣的部分是,当服务器作为 localhost 运行时它可以完美运行,但当服务器位于远程计算机上时它就不行了。接收到的 blob 大小是准确的,但使用 FileSaver.saveAs 将 blob 保存到文件会生成一个空文件。不知道问题出在哪里?

function downloadResultsZip(id, reqDelay) {
let uri = `https://etc...`;
let delay = 0;
let timerId = setTimeout(function request() {
    fetch(uri).then(function (response) {
        if (response.status === 202) { // Request accepted.
            delay = reqDelay;
            timerId = setTimeout(request, delay);
        } else if (response.status === 200) { // OK
            let zipFileName = response.headers.get('Content-Disposition').match(/.*"(.*)".*/)[1];
            //
            response.blob().then(function (zipBlob) {
                clearTimeout(timerId);
                //alert("zipBlob size = " + zipBlob.size); // ok, accurate
                FileSaver.saveAs(zipBlob, zipFileName); // Problem!
            });
        } else {
            if (response.status === 400) { // Bad Request
                alert('Server responded with an error: \"input parameters are not valid\".');
            } else {
                alert('Error! Server calculation has failed.');
            }
            clearTimeout(timerId);
        }
    });
}, delay);

}

第一次编辑。

我刚刚发现源代码是正确的,但仅在 Firefox 71 中无法按预期工作。在 Chrome 79 和 Edge 44 (EdgeHTML 18) 中可以正常工作。由于我对 JS 很陌生,我想知道如何克服这个问题。我还尝试了创建指向 URI 服务的标记和 href 属性然后单击该链接的基本方法,但我成功地只保存了大约 1 KB 的数据,而不是预期的 5.3 MB。

标签: javascriptfirefoxblobfilesaver.js

解决方案


推荐阅读