【问题标题】:Getting corrupted word document when using FileSaver and Blob in angularjs在angularjs中使用FileSaver和Blob时得到损坏的word文档
【发布时间】:2016-04-21 18:53:44
【问题描述】:

我正在使用角度文件保护服务https://github.com/alferov/angular-file-saver 下载文件。下载很好,但是当尝试打开word文档时,我得到的文件已损坏,word无法打开它,如果将我的api直接放在浏览器文件中,当我打开它时很好,所以我想blob正在为这个问题做一些事情......对于.txt 文件我没有损坏它只适用于 .docx 和 .jpeg 或 .png。下面是我下载文件的短代码。

function downloadDocument(fileId, fileName, documentExt) {
            var deferred = $q.defer();

            var id = encodeURIComponent(fileId);
            Restangular.one('download?fileId=' + id).get().then(function(data) {
                var file = new Blob([data]);
                if (documentExt && documentExt !== 'undefined') {
                    FileSaver.saveAs(file, fileName + '.' + documentExt);
                }
                else {
                    FileSaver.saveAs(file, fileName);
                }
            });

            return deferred.promise;
        }

【问题讨论】:

    标签: javascript angularjs blob filesaver.js


    【解决方案1】:

    你可以使用下面的代码来保存你的文件——

    function downloadDocument(fileId, fileName, documentExt) {
                var deferred = $q.defer();
    
                var id = encodeURIComponent(fileId);
                Restangular.one('download?fileId=' + id).get().then(function(data) {
                    // try to use data.data or data in blob object
                     var file = new Blob([data.data], {
                        type: 'application/octet-binary'
                    });
                    var fileUrl = URL.createObjectURL(file);
                    // for IE 10+
                    if (window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveOrOpenBlob(file, fileName+'.'+documentExt);
                    } else {
                        var element = document.createElement('a');
                        element.href = fileUrl;
                        element.setAttribute('download', fileName+'.'+documentExt);
                        element.setAttribute('target', '_blank');
                        document.body.appendChild(element); 
                        element.click();
                    }
                });
    
                return deferred.promise;
            }
    

    【讨论】:

    • 嘿 Shaliendra,服务器端不是问题,例如我在调用此函数时指向的这个 api 调用:localhost:8080/… 如果我直接将其放入浏览器并尝试打开文件以 word 下载它正在工作它也没有损坏。
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多