使用laravel 自带的上传功能

发布时间:2023-10-11 15:56:15 浏览次数:410

laravel 自带的上传功能

1.文件上传配置
项目目录下面config->filesystems.php,其中有一个disk的配置。

image.png


添加一个自定义的驱动public,设置文件上传路径,这里设置为storage目录下面的app文件夹:


image.png


2.模板页面

{!! Form::open(['route' => 'order.store', 'class'=>'form-horizontal mt-20', 'enctype' => 'multipart/form-data']) !!}
  <div class="form-group">
    <label class="col-sm-2 control-label label-width">图片:</label>
    <div class="col-sm-10">
        <input type="file" name="picture" id="picture" required="true">
    </div></div><div class="form-group">
    <label class="col-sm-2 control-label label-width"></label>
    <div class="col-sm-10 mb-15">
        <button type="submit" class="btn btn-primary">提交</button>
    </div>
  </div>
{!! Form::close() !!}

2.在OrderController控制器里面

使用命名空间

use App\Models\Order;use Illuminate\Support\Facades\Storage;

store 方法中对上传文件进行处理

public functiuon store(REQUEST $request) {
    $data = $request->all();
    $picture = $request->file('picture'); 

    if ($picture->isValid()) {
       $ext = $picture->getClientOriginalExtension();
       $path = $picture->getRealPath(); 
       $filename = 'data/upload/'.time().mt_rand(999, 9999).'.'.$ext; //文件路径,存入数据库
       Storage::disk('public')->put($filename, file_get_contents($path));
    }
    $data['picture'] = $filename;
    Order::create($data);
}



最新文章
备案号:赣ICP备2022011147号-1
备案号:赣ICP备2022011147号-2