圖片上傳控制器代碼
// 文件上傳方法
public function upload(Request $request)
{
if ($request->isMethod('post')) {
$file = $request->file('picture');
// 文件是否上傳成功
if ($file->isValid()) {
// 獲取文件相關信息
$originalName = $file->getClientOriginalName(); // 文件原名
$ext = $file->getClientOriginalExtension(); // 擴展名
$realPath = $file->getRealPath(); //臨時文件的絕對路徑
$type = $file->getClientMimeType(); // image/jpeg
// 上傳文件
$filename = uniqid() . '.' . $ext;
// 使用我們新建的uploads本地存儲空間(目錄)
//這里的uploads是配置文件的名稱
$bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
exit('{"src":"' . $realPath . '"}');
exit;
}
}
return view('upload');
}
上傳路徑配置
config>filestream.conf
// 新建一個本地端uploads空間(目錄) 用於存儲上傳的文件
'uploads' => [
'driver' => 'local',
// 文件將上傳到storage/app/uploads目錄
//'root' => storage_path('app/uploads'),
// 文件將上傳到public/uploads目錄 如果需要瀏覽器直接訪問 請設置成這個
'root' => public_path('uploads'),
],
圖片上傳前端代碼
<form method="post" action="{{url('/blue_cross_admin/article/add')}}" enctype="multipart/form-data">
<div class="form-group">
<label for="file">標題插圖:</label>
<input type="file" name="picture" data-id="icon" class="img myfile"/><span style="color: #cccccc">(圖片大小為:355*300)</span>
</div>
<button type="submit" class="btn btn-primary">添加</button>
<button type="reset" class="btn btn-danger">取消</button>
</form>
