簡體   English   中英

從 Laravel 中的存儲返回文件下載

[英]Return file download from storage in Laravel

我希望能夠從我的 controller 中的存儲中檢索文件。

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        $fileGet = Storage::get($file->file_path);
        return $fileGet;
    }
}

現在,我能夠正確獲取路徑,但是,出現的所有內容都是胡言亂語,就好像您正在查看沒有擴展名的圖像一樣。

理想情況下,我希望這可以作為“另存為”之類的東西。

我怎樣才能做到這一點?

您應該使用文件下載響應

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        return response()->download(storage_path('app/' . $file->file_path));
    }
}

返回一個字符串是不好的做法。 使用Laravel響應時 ,Laravel確保正確設置標頭和其他要求以將響應返回給瀏覽器。

您可以使用方法download而不是get Storage門面。

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        return Storage::download($file->file_path);
    }
}

暫無
暫無

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

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