【问题标题】:Why does my download feature (created using Vue JS and Laravel) result in corrupted files?为什么我的下载功能(使用 Vue JS 和 Laravel 创建)会导致文件损坏?
【发布时间】:2020-06-21 12:28:43
【问题描述】:

我目前正在开发一种下载功能,该功能允许用户下载他们上传的文件(所有类型)。下载功能有效(因为文件出现在我的下载文件夹中,并且文件类型已在文件名旁边显示的图像中注册),但是由于某种原因,我下载的所有文件都被视为已损坏或格式错误。

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');

我的控制器:

public function downloadSomeFile($id)
{
    $downloadFile = File::find($id);
    Storage::download(str_replace('/File', '', $downloadFile->path));
}

有办法解决吗?

以下是我尝试打开下载文件时收到的消息示例:

【问题讨论】:

    标签: laravel file vue.js download axios


    【解决方案1】:

    如果你想下载一个非文本文件,你必须在你的 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);
            });
    },
    

    【讨论】:

    • 我尝试添加它,但它似乎不起作用。文件仍然损坏,您认为它可能与控制器有关吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多