首页 > 解决方案 > 上传图片有问题。我正在使用 Laravel + Vue + vuetify

问题描述

我有一个代码,我想使用 Vue 保存图像,Laravel 将路线保存在数据库中

控制器:

public function update(Request $request, $id){
      $home = Home::findOrFail($id);
      $home->background = $request->background;
      $home->title = $request->title;
      $home->subtitle = $request->subtitle;
      $home->icon_go = $request->icon_go;

      $fileName = $request->image;

      $path = $_SERVER['DOCUMENT_ROOT'].'assets/images/'.$fileName;
      $home->image =  $path;

      $home->update();
      file_put_contents($path, $fileName);

      return response()->json([
           'status'=> 200,
            'title' => 'Home Update',
           'data'  => $home,
      ]);
}

输入:

<v-col cols="12" sm="12" md="12">
    <input type="file"
        @change="getImage"
        label="Imagen" 
        required
        :class="{ 'is-invalid' : form.errors.has('image') }">

        <has-error :form="form" field="image"></has-error>
 </v-col>

只有我只是输入,表单工作正常

功能更新:

update(){
//Update a resource
this.$Progress.start()
this.form.busy = true;
this.form.image = this.form.image.name
this.form.put('/api/v1/home/' + this.form.id)
        .then(response => {
            this.getHome()
            if (this.form.successful) {
                this.$Progress.finish()
                this.updateNotify()
            }else{
                this.$Progress.fail() 
                this.$snotify.error('¡Ha ocurrido un error!', 'Error')
            }
        })
        .catch(e => {
            this.$Progress.fail() 
            console.log(e)
        })
  }, 

问题可能出在控制器中,但我无法检测到。我会很感激你的帮助。

唯一不起作用的是图像没有显示内容

照片保存在文件夹 public / assets / images这就是图像在文件夹中的保存方式

标签: laravelvue.js

解决方案


尝试使用下面的代码。由于 $request->image 不会给出文件对象。相反,我们需要使用 file() 帮助程序。

public function update(Request $request, $id){
      $home = Home::findOrFail($id);
      $home->background = $request->background;
      $home->title = $request->title;
      $home->subtitle = $request->subtitle;
      $home->icon_go = $request->icon_go;

      $file = $request->file('image'); //gets the image file

      $path = $_SERVER['DOCUMENT_ROOT'].'assets/images/';
      $home->image =  $path.$file->getClientOriginalName();

      $home->update();

      $file->move($path, $file->getClientOriginalName()); //stores in location

      return response()->json([
           'status'=> 200,
            'title' => 'Home Update',
           'data'  => $home,
      ]);
}

推荐阅读