laravel 文件上傳方法
第一步:創建本地磁盤
在 config中找到filesystems.php
,裏面新增一個uploads
磁盤
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
'uploads' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],
第二步在控制器中創建方法
public function uploads(Request $request)
{
if($request->isMethod('POST')){
$files = $request->file('carid');
// 文件是否上傳成功
if($files->isValid()){
// 原文件名
$originalName = $files->getClientOriginalName();
// 擴展名
$ext = $files->getClientOriginalExtension();
// 文件類型
$type = $files->getMimeType();
// 臨時文件絕對路徑
$realPath = $files->getRealPath();
// 要保存在項目中的文件名
$filesName = date('Y-m-d-H-i-s'). '-'.uniqid().'.'.$ext;
// 執行保存至本地磁盤
$bool = Storage::disk('uploads')->put($filesName,file_get_contents($realPath));
// var_dump($bool);
$data = [
'code' => $bool?0:1,
'msg' => '',
'data'=>$bool ? $filesName:'',
];
return response()->json($data);
}
exit;
}
return view('student.upload');
}