【问题标题】:I cant download a zip file in AngularJS (from Laravel response)我无法在 AngularJS 中下载 zip 文件(来自 Laravel 响应)
【发布时间】:2020-03-16 13:33:50
【问题描述】:

我正在尝试使用 Angular JS 从 Laravel API 下载 zip 文件。我不相信这个问题来自 Laravel。

基本上,当响应到来并触发下载时,它不知道它是一个 .zip 文件,但文件本身是好的。但是,当我在文件名中手动添加 Angular JS 中的 .zip 扩展名时,浏览器会提示其文件损坏。

如果我不添加扩展名,它可以正常下载,然后如果我在 Windows 中重命名没有扩展名的文件并将其更改为test.zip,它可以完美地作为一个 zip 文件运行。这就是我知道数据良好的方式。

我试过arraybuffer responseType 和blob。使用blob 我得到了下载触发器,使用arraybuffer 什么都没有发生(包括没有控制台错误)。

这是我的 JS 控制器代码:

vm.downloadSelectedFiles = function() {
    vm.selectedFiles = [];
    angular.forEach(vm.fileDownloadList, function(value,index) {
        if(value==1) {
            vm.selectedFiles.push(index);
        }
    });
    Data.downloadSelectedFiles(vm.selectedFiles,vm.stationIDToLookUp)
     .then(function (data) {
        var url = $window.URL || $window.webkitURL;
        vm.fileUrl = url.createObjectURL(data.data);
        var a = document.createElement("a");
        a.href = vm.fileUrl;
        a.download = 'test.zip';
        //a.download = 'test';
        a.click();

    }).catch(function (err) {
    });
}

这是我的 JS 服务代码

    downloadSelectedFiles: function downloadSelectedFiles(selectedFiles,stationID) {
        var apiBase = apiUrl + 'download-selected-files';
        var config = {
            //responseType: 'arraybuffer'
            responseType: 'blob'
        };
        var data = {
            selectedFiles: selectedFiles,
            stationID: stationID
        }

        return $http.post(apiBase, data, config);
    }

以防万一 API 的响应有相关性。这是我的 Laravel 代码

public function downloadSelectedFiles(PublishDataRequest $requestData) {
    return response()->file(storage_path() . '/app/files/test.zip');
}

【问题讨论】:

  • 下载的 Blob 的Blob.type 的值是多少?它会更好,它是application/zip。

标签: angularjs laravel zip blob


【解决方案1】:

尝试将 MIME 类型设置为application/zip:

Data.downloadSelectedFiles(vm.selectedFiles,vm.stationIDToLookUp)
 .then(function (response) {
    var blob = response.data;
    var zipBlob = new Blob([blob], { type: "application/zip" });
    var url = $window.URL || $window.webkitURL;
    vm.fileUrl = url.createObjectURL(zipBlob);
    var a = document.createElement("a");
    a.href = vm.fileUrl;
    a.download = 'test.zip';
    //a.download = 'test';
    a.click();
}).catch(function (response) {
    console.log("ERROR", response);
    throw response;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2019-02-05
    • 1970-01-01
    • 2020-02-07
    • 2020-04-15
    相关资源
    最近更新 更多