【问题标题】:Error in uploading photo in laravel with vue.js使用 vue.js 在 laravel 中上传照片时出错
【发布时间】:2019-12-14 18:39:37
【问题描述】:

我正在使用 laravel 和 vuejs 和 vue-router 制作单页应用程序。我正在为我的 http 请求使用 api.php 路由。每当我在我的news 表中保存带有图像的数据时,它都会向我显示一个错误。我需要做什么? NewsController.php

<?php

namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\News;
class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return News::latest()->paginate(10);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|string|max:191|unique:news',
            'subtitle' => 'required|string|max:191',
            'body' => 'required|string',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ]);


        $news = new News;
        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/news/' . $filename);
                \Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
        }

        $news->save();
    }
}

News.vue

<!-- Vform -->
                                  <form @submit.prevent="createNews()">
                                    <div class="form-group">
                                    <label>News Title</label>
                                    <input
                                    v-model="form.title"
                                    type="text" name="title"
                                    placeholder="Title"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('title') }">
                                    <has-error :form="form" field="title"></has-error>
                                    </div>

                                    <div class="form-group">
                                    <label>Subtitle</label>
                                    <input
                                    v-model="form.subtitle"
                                    type="text"
                                    name="subtitle"
                                    placeholder="Subtitle"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('subtitle') }">
                                    <has-error :form="form" field="subtitle"></has-error>
                                    </div>

                                    <div class="form-group">
                                    <label>News Content</label>
                                    <textarea
                                    v-model="form.body"
                                    type="text"
                                    name="body"
                                    placeholder="News Content"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('body') }">
                                    </textarea>
                                    <has-error :form="form" field="body"></has-error>
                                    </div>


                                    <div class="form-group">
                                    <label>Picture</label>
                                    <input type="file" id="image"
                                    class="form-control" :class="{ 'is-invalid': form.errors.has('image') }">
                                    <has-error :form="form" field="image"></has-error>
                                    </div>


                        <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                         <!-- <button  v-show="editmode" type="submit" class="btn btn-primary">Update</button> -->
                        <button type="submit" class="btn btn-success">Create</button>
                         </div>
                        </form>
                        <!-- vform -->

<script>
    export default {
        data(){
            return{
                news: {},
                form: new Form({
                    id:"",
                    title: "",
                    subtitle:"",
                    body:"",
                    image:"",
                    postedby:""
                })
            }
        },

        methods: {
            loadNews(){
                axios.get('api/news')
                    .then(({data}) => (this.news = data))
            },
            createNews(){
                this.$Progress.start()
                this.form.post("api/news")
                    .then(()=>{
                         $("#addNews").modal("hide")
                         $(".modal-backdrop").remove()
                        swal.fire("Created!", "", "success")
                    })
                this.$Progress.finish()
            },
        },

        created() {
            console.log('Component mounted.')
            this.loadNews()
        }
    }
</script>

api.php

Route::apiResource('news', 'API\NewsController');

【问题讨论】:

    标签: laravel vue.js upload vue-component


    【解决方案1】:

    您是否检查过您使用的是多部分/表单数据编码?

    编辑: https://github.com/cretueusebiu/vform/blob/master/example/upload.html

    【讨论】:

    • 我只使用了一个名为vform 的包,我按照那里的说明进行操作,我可以提交除图像之外的所有数据
    • 不要犹豫,看看 github 问题 ;) github.com/cretueusebiu/vform/issues/12 这里有人遇到了同样的问题。您需要将对象转换为 FormData。 github.com/cretueusebiu/vform/blob/master/example/upload.htmldeveloper.mozilla.org/en-US/docs/Web/API/FormData
    • 所以我的控制器没有问题,先生?我觉得很难理解,但我很难理解它
    • 不知道你的控制器是否正常。如果我是你,我会首先检查我的表格是否正确编码。您可以使用您的开发人员工具进行检查。打开它,使用“网络”选项卡,然后发送您的表格。您应该会看到您的请求已发送。单击它,然后单击“标题”。然后向下滚动,您应该会看到您的请求数据。它应该被命名为“FormData”。点击“查看源代码”。您应该看到 ------WebKitFormBoundary 等。此外,它会通知您使用的 Content-Type。然后如果没问题,你可以检查你的控制器。
    • 每当我将一些文件放入其中时,我的image 字段中没有任何变化。但是当我在表单的标题中输入一些文字时,表单数据中的title立即改变了先生。
    【解决方案2】:

    将此代码放入您的 Vue 文件中

     <div class="col-sm-12">
                      <input
                        type="file"
                        @change="updateImage"
                        class="form-input"
                        :class="{ 'is-invalid': form.errors.has('image') }"
                        id="image"
                        name="image"
                      />
                      <has-error :form="form" field="image"></has-error>
                    </div>
    
    <script>
        export default {
            data(){
                return{
                    news: {},
                    form: new Form({
                        id:"",
                        title: "",
                        subtitle:"",
                        body:"",
                        image:"",
                        postedby:""
                    })
                }
            },
    
            methods: {
    updateImage(e) {
          let file = e.target.files[0];
          console.log(file);
          let reader = new FileReader();
          if (file["size"] < 2111775) {
            reader.onloadend = file => {
              this.form.image= reader.result;
            };
            reader.readAsDataURL(file);
          } else {
            swal.fire({
              type: "error!",
              title: "Oops...",
              text: "Your are uploading a large File "
            });
    
            // return ["warning", "file size"];
            Fire.$emit("refreshPage");
          }
        },
                loadNews(){
                    axios.get('api/news')
                        .then(({data}) => (this.news = data))
                },
                createNews(){
                    this.$Progress.start()
                    this.form.post("api/news")
                        .then(()=>{
                             $("#addNews").modal("hide")
                             $(".modal-backdrop").remove()
                            swal.fire("Created!", "", "success")
                        })
                    this.$Progress.finish()
                },
            },
    
            created() {
                console.log('Component mounted.')
                this.loadNews()
            }
        }
    </script>
    

    你的控制器代码是

    <?php
    
    namespace App\Http\Controllers\API;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\News;
    class NewsController extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            return News::latest()->paginate(10);
        }
    
        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function store(Request $request)
        {
            $this->validate($request, [
                'title' => 'required|string|max:191|unique:news',
                'subtitle' => 'required|string|max:191',
                'body' => 'required|string',
                'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
            ]);
    
    
            $news = new News;
            $news->title = $request->title;
            $news->subtitle = $request->subtitle;
            $news->body = $request->body;
            if ($request->hasFile('image')){
    $name = time().'.'.explode('/',explode(':',substr($request->image,0,strpos($request->image,';')))[1])[1];
                        \Image::make($request->image)->save(public_path('img/news/').$name);
    
    
                //Update DB
                    $news->image = $name ;
    
            }
    
            $news->save();
        }
    }
    

    如果有效,请告诉我,我将提供更新代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2016-08-08
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2021-08-06
      • 2014-09-18
      相关资源
      最近更新 更多