我目前正在开发一项下载功能,该功能允许用户下载他们上传的文件(所有类型)。下载功能有效(如我的下载文件夹中显示的文件,并且文件类型已在文件名旁边显示的图像中注册),但是由于某种原因,我下载的所有文件都被视为已损坏或属于格式错误。
Axios 请求(在方法内):
downloadFile(file) {
axios.get(window.routes.files.download.replace("_id_", file.id), {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/vnd.ms-excel'
}
})
.then(function(response){
if (!window.navigator.msSaveOrOpenBlob){
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', file.name);
document.body.appendChild(link);
link.click();
}else{
const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),file.name);
}
console.log(response.data);
})
.catch(function(error){
console.error(error);
if (!!error.response) console.log(error.response);
});
},
Laravel 路线:
Route::get('files/{file}', 'FileController@downloadSomeFile')->name('files.download');
我的 Controller :
public function downloadSomeFile($id)
{
$downloadFile = File::find($id);
Storage::download(str_replace('/File', '', $downloadFile->path));
}
有办法解决吗?
下面是我尝试打开下载的文件时收到的消息示例:
最佳答案
如果你想下载非文本文件,你必须在ajax中设置responseType。
downloadFile(file) {
axios.get(window.routes.files.download.replace("_id_", file.id), {
headers: {
'Accept': 'application/vnd.ms-excel'
},
responseType: 'arraybuffer' //<-- here
})
.then(function(response){
if (!window.navigator.msSaveOrOpenBlob){
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', file.name);
document.body.appendChild(link);
link.click();
}else{
const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),file.name);
}
console.log(response.data);
})
.catch(function(error){
console.error(error);
if (!!error.response) console.log(error.response);
});
},
关于laravel - 为什么我的下载功能(使用 Vue JS 和 Laravel 创建)会导致文件损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60603552/