我正在尝试使用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');
}
答案 0 :(得分:0)
尝试将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;
});