簡體   English   中英

axios 下載每個帶有txt擴展名的文件

[英]axios download every file with txt extension

我嘗試從 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();
        });
    }

Laravel:

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

使用Storage::download代替:

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

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

    abort(404);
 }

這是文檔

呃...為什么要浪費時間用 axios 將它作為 blob 下載然后保存? 為什么不直接執行fileLink.href = url並直接下載而不浪費任何 RAM?

似乎您要做的一切都是這樣的:

location = '/api/user/downloadFile/' + id

或這個:

<a href="/api/user/downloadFile/123">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM