【问题标题】:Image upload from front-end从前端上传图片
【发布时间】:2020-11-27 18:16:44
【问题描述】:

我正在尝试在 OctoberCMS 中从前端上传图像文件

我有一个模型人物和关系:

public $attachOne = [
    'photo' => 'System\Models\File'
];

在带有上传表单的 php-block 中:

public function onUploadImage() {
    $person = Person::where('id', '=', $this->param('id'))->first();
    $person->photo = \Input::file('avatar');
    $person->save();
}

还有我的模板:

<form method="POST" action="/persons/person/{{person.id}}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_handler" value="onUploadImage">
<input type="file" name="avatar" id="avatar" />

{{ form_token() }}
{{ form_sessionKey() }}

<button type="submit" data-attach-loading>Upload</button>

提交后,它只保存到数据库路径“http://my-site/storage/app/uploads/public/”,并且不会将任何文件上传到文件系统。好像没有什么权限,但我可以很容易地从后端上传图片。

我的错误在哪里?

【问题讨论】:

    标签: php laravel octobercms


    【解决方案1】:

    您必须从请求中获取 UploadedFile 并将其存储到配置的磁盘之一。并将图片的路径存入数据库。

    假设storage/app/public/images是上传图片的存放目录。

    public function onUploadImage() {
    
        if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
    
            $file = request()->file('avatar');
            $filename = $file->getClientOriginalName();
    
            $person = Person::where('id', '=', $this->param('id'))->first();
            $person->photo = $file->storeAs('images', $filename)
            $person->save();
        }
    }
    

    【讨论】:

      【解决方案2】:

      Here 是解决方案。

      if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
      
              $file = new System\Models\File;
              $file->data = Input::file('avatar');
              $file->is_public = true;
              $file->save();
      
              $person = Person::where('id', '=', $this->param('id'))->first();
              $person->photo()->add($file);
              $person->save();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-29
        • 2019-08-01
        • 2013-06-21
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多