在config下新建文件admin.php,定义上传文件的路径
'upload_img_path' =>'app/public/img',//本地上传图片路径
'upload_file_path' =>'app/public/files'//本地上传文件路径
在config/filesystems.php下定义
- 'disks' => [
- 'uploadimg'=>[
- 'driver'=>'local',
- 'root'=>storage_path(config('admin.upload_img_path'))
- ],
- 'uploadfiles'=>[
- 'driver'=>'local',
- 'root'=>storage_path(config('admin.upload_file_path'))
- ],
-
- 'local' => [
- 'driver' => 'local',
- 'root' => storage_path('app'),
- ],
-
- 'public' => [
- 'driver' => 'local',
- 'root' => storage_path('app/public'),
- 'url' => env('APP_URL').'/storage',
- 'visibility' => 'public',
- ],
-
- 's3' => [
- 'driver' => 's3',
- 'key' => env('AWS_KEY'),
- 'secret' => env('AWS_SECRET'),
- 'region' => env('AWS_REGION'),
- 'bucket' => env('AWS_BUCKET'),
- ],
-
- ],
后台上传方法
- public function uploadImg(Request $request){
-
- $wenjian= $request->file('files');
- if ($wenjian) {
-
- //获取文件的原文件名 包括扩展名
- $yuanname= $wenjian->getClientOriginalName();
-
- //获取文件的扩展名
- $kuoname=$wenjian->getClientOriginalExtension();
-
- //获取文件的类型
- $type=$wenjian->getClientMimeType();
-
- //获取文件的绝对路径,但是获取到的在本地不能打开
- $path=$wenjian->getRealPath();
-
- //要保存的文件名 时间+扩展名
- $filename=date('Y-m-d') . '/' . uniqid() .'.'.$kuoname;
- //保存文件 配置文件存放文件的名字 ,文件名,路径
- $bool= Storage::disk('uploadimg')->put($filename,file_get_contents($path));
- //return back();
- return json_encode(['status'=>1,'filepath'=>$filename]);
- }else{
- $idCardFrontImg = '';
- return json_encode($idCardFrontImg);
- }
- }
前台显示
- <img src="/storage/img/2018-04-27/5ae294e2830df.jpeg">
在写接口上传的照片如何保存到public让前端框架访问到,,就要建立软连接将照片放到public目录去访问! 很简单
执行命令:php artisan storage:link
命令执行完毕后,就会在项目里多出一个 public/storage,
这个 storage 就是一个软链接,它指向 storage/app/public 目录。
public/storage(软连接) → storage/app/public
然后就可以用地址直接访问public里面的照片了!
以上这篇laravel 实现上传图片到本地和前台访问示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。