使用Angular文件保存器下载大型文件

6

我已经在我的项目中使用angular file saver实现了文件下载功能,对于小文件它可以正常工作。但是对于大于50MB的文件,下载会在35-50MB后停止,并显示以下错误信息。

net::ERR_INCOMPLETE_CHUNKED_ENCODING

我在互联网上尝试调查了这个问题,并发现下载限制为500MB,因为很明显无法将如此多的信息存储在RAM中。不幸的是,我没有找到任何其他解释如何解决这个问题,然后我问了后端工程师,得到的答案是他那边一切正常。

那么我的问题在哪里?我该如何解决这个问题?感谢任何帮助。

以下是我的代码的一部分:

服务

 function attachment(obj) {
        custom.responseType = "arraybuffer";
        delete  custom.params.limit;
        delete  custom.params.offset;
        delete  custom.params.orderBy;
        delete  custom.params.insertedAt;

        var contentType = obj.mimeType;
        var name =  obj.displayFilename;

        return $http.get(Config.rurl('attachments') + '/' + obj.bucketName + '/' + obj.path + '?displayFilename=' + obj.displayFilename, custom)
            .then(function (response) {
                var data = new Blob([response.data], { type: contentType });
                FileSaver.saveAs(data, name);
                delete custom.responseType
            })
            .catch(function (err) {
                delete custom.responseType;
                alert("It has happened an error. Downloading has been stopped") ;
            });
    }

控制器函数

$scope.download = function (obj) {
        lovServices.attachment(obj)
    }

你解决了吗?我试图下载一个Excel文件,但是在处理大文件时遇到了相同的问题。https://stackoverflow.com/questions/72636282/downloading-large-excel-file-in-angular-using-xlsx-libraryneterr-incomplete-c - user2868864
1个回答

7

不要将文件下载到内存并转换为blob。将responseType设置为'blob'

//SET responseType to 'blob'
var config = { responseType: ̶'̶a̶r̶r̶a̶y̶b̶u̶f̶f̶e̶r̶'̶ ̶ 'blob' };

return $http.get(url, config)
    .then(function (response) {
        ̶v̶a̶r̶ ̶d̶a̶t̶a̶ ̶=̶ ̶n̶e̶w̶ ̶B̶l̶o̶b̶(̶[̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶]̶,̶ ̶{̶ ̶t̶y̶p̶e̶:̶ ̶c̶o̶n̶t̶e̶n̶t̶T̶y̶p̶e̶ ̶}̶)̶;̶
        //USE blob response 
        var data = response.data;
        FileSaver.saveAs(data, name);
    })
    .catch(function (err) {
        alert("It has happened an error. Downloading has been stopped") ;
        throw err;
    });

这样做避免了将流转换为arraybuffer,然后再重新生成blob的内存开销。
更多信息,请参见MDN XHR API ResponseType

1
由于这是一个AJAX请求,调用saveAs()之前必须将完整的文件内容加载到浏览器内存中,对吗?这意味着对于非常大的文件,刷新页面将会丢失所有文件内容? - losmescaleros
1
Blob 是一种类似于流的异步外来对象。ArrayBuffer 是一种内存对象。通过将XHR responseType设置为Blob,避免了将其加载到JavaScript内存中的步骤。JavaScript在加载之前将流传递给FileSaver。 - georgeawg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接