我无法在AngularJS中下载zip文件(来自Laravel响应)



我正在尝试使用Angular JS从Laravel API下载一个zip文件。我不认为这个问题来自拉拉威尔。

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

如果我不添加扩展名,它下载得很好,然后如果我在Windows中重命名没有扩展名的文件并将其更改为test.zip,它就可以完美地作为zip文件使用。这就是我如何知道数据是好的。

我尝试过arraybufferresponseType和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');
}

尝试将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;
});

最新更新