首页 > 解决方案 > axios 下载每个带有 txt 扩展名的文件

问题描述

我尝试从 laravel 的服务器下载任何文件,但所有文件都下载为 .txt 文件

在此处输入图像描述 这是我的 javascript 代码:

        downloadAttachment:function (id){
        axios({
            url: '/api/user/downloadFile/'+id,
            method: 'GET',
            responseType: 'blob',
        }).then((response) => {
            let fileURL = window.URL.createObjectURL(new Blob([response.data]));
            let fileLink = document.createElement('a');
            fileLink.href = fileURL;
            fileLink.setAttribute('download', response.data.type);
            document.body.appendChild(fileLink);
            fileLink.click();
        });
    }

拉拉维尔:

    public function downloadDocument($file)
{
    $path=$file->src;
    if(Storage::exists($path))
    {
        $file=Storage::get($path);
        $type=Storage::mimeType($path);
        $response = Response::make($file, 200);
        $response->header("Content-Type", $type);
        return $response;
    }
    abort(404);
 }

标签: javascriptlaravelvue.js

解决方案


改用Storage::download

public function downloadDocument($file)
{
    $path = $file->src;

    if (Storage::exists($path)) {
        return Storage::download($path);
    }

    abort(404);
 }

这是文档


推荐阅读