[筆記]laravel的上傳檔案或者圖片的方法

Laravel00發表於2021-12-03

一個上傳檔案或者圖片的方法,在這裡做一下筆記

public function fileUpload(Request $request)
{
    if ($request->hasFile('picture')) {
        $picture = $request->file('picture');
        if (!$picture->isValid()) {
            abort(400, '無效的上傳檔案');
        }
        // 副檔名
        $extension = $picture->getClientOriginalExtension();
        // 檔名
        $fileName = $picture->getClientOriginalName();
        // 生成新的統一格式的檔名
        $newFileName = md5($fileName . time() . mt_rand(1, 10000)) . '.' . $extension;
        // 圖片儲存路徑
        $savePath = 'images/' . $newFileName;
        // Web 訪問路徑
        $webPath = '/storage/' . $savePath;
        // 將檔案儲存到本地 storage/app/public/images 目錄下,先判斷同名檔案是否已經存在,如果存在直接返回
        if (Storage::disk('public')->has($savePath)) {
            return response()->json(['path' => $webPath]);
        }
        // 否則執行儲存操作,儲存成功將訪問路徑返回給呼叫方
        if ($picture->storePubliclyAs('images', $newFileName, ['disk' => 'public'])) {
            return response()->json(['path' => $webPath]);
        }
        abort(500, '檔案上傳失敗');
    } else {
        abort(400, '請選擇要上傳的檔案');
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
溫馨提示:微信搜尋並關注   學Laravel  裡面有兩套Laravel課程:【laravel7.x 從入門到核心架構講解】 與 【Laravel高階實戰教程42集】,直接獲取就可以了,學習與交流可加入:Laravel技術交流微信群

相關文章