新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
laravel中如何實(shí)現(xiàn)單文件、多文件上傳功能-創(chuàng)新互聯(lián)
這篇文章給大家分享的是有關(guān)laravel中如何實(shí)現(xiàn)單文件、多文件上傳功能的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
先設(shè)置上傳文件的路由:
Route::post('upload/images'['as'=>'uploadImages','uses'=>'UploadController@uploadImages']); Route::post('upload/multiUpload'['as'=>'multiUpload','uses'=>'UploadController@multiUpload']);
再設(shè)置uploads磁盤地址,之后儲(chǔ)存文件會(huì)使用到。config / filesystem : disks
'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], 'uploads'=>[ 'driver'=>'local', 'root'=>public_path('uploads/'), ] ],
最后UploadController定義上傳函數(shù)(使用Storage的disk方法來訪問uploads磁盤,就是前面filesystem文件里設(shè)置的)
putFile方法:管理文件到指定的存儲(chǔ)位置,例為自動(dòng)生成文件名,也可以手動(dòng)設(shè)置 ('20190705', $file,'test.png')
//上傳單張圖 public function uploadImages(Request $request) { if ($request->isMethod('post')) { $file = $request->file('file'); if($file->isValid()){ $path = Storage::disk('uploads')->putFile(date('Ymd') , $file); if($path) { return ['code' => 0 , 'msg' => '上傳成功' , 'data' => $path]; } else { return ['code' => 400 , 'msg' => '上傳失敗']; } } } else { return ['code' => 400, 'msg' => '非法請(qǐng)求']; } } //上傳多張圖 public function multiUpload(Request $request) { if($request->method('post')){ $files = $request->allFiles(); if(is_array($files)){ foreach($files as $file){ $path = Storage::disk('uploads')->putFile(date('Ymd') , $file); } if( $path ) { return ['code' => 0 , 'msg' => '上傳成功' , 'data' => $path]; } else { return ['code' => 400 , 'msg' => '上傳失敗']; } } }else{ return ['code' => 400, 'msg' => '非法請(qǐng)求']; } }
感謝各位的閱讀!關(guān)于“l(fā)aravel中如何實(shí)現(xiàn)單文件、多文件上傳功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
文章標(biāo)題:laravel中如何實(shí)現(xiàn)單文件、多文件上傳功能-創(chuàng)新互聯(lián)
標(biāo)題URL:http://www.dlmjj.cn/article/hhsed.html