【问题标题】:Invalid argument supplied for foreach() vue js in laravellaravel 中为 foreach() vue js 提供的参数无效
【发布时间】:2021-07-06 14:20:39
【问题描述】:

我无法在我的 Laravel + vue js 项目中上传多张图片..

下面是我的代码

我的 vue 组件

<form @submit.prevent="addProduct" enctype="multipart/form-data">
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-lg-4">
                                            <label for="product_image">Product Image:</label>
                                        </div>
                                        <div class="col-lg-4">
                                            <input type="file" name="pics[]" id="product_image" @change="fieldChange" multiple>
                                            <has-error :form="form" field="product_image"></has-error>
                                        </div>
                                        <div class="col-lg-4">
                                            <img :src="form.product_image" height="70px" width="85px" alt="">
                                        </div>
                                    </div>
                                </div>

</form>

我使用FormData上传图片

    data: function(){
            return{
                attachment:[],
                imageForm : new FormData,
            }
        },
        methods:{
            fieldChange(e){
                let selectedFiles = e.target.files;
                if (!selectedFiles.length) {
                    return false;
                }
                for(let i=0;i<selectedFiles.length;i++){
                    this.attachment.push(selectedFiles[i])
                }
                console.log(this.attachment);
                 //I checked here ang got image arrays
            },
            addProduct:function(){
                for(let i=0;i<this.attachment.length;i++){

                this.imageForm.append('pics[]',this.attachment[i]);

                //When I console.log() this line it says undefined
                }
                axios.post('/save-product',this.form,this.imageForm).then((response)=>{
                        toastr.success('Product Info Added Successfully','Success!');
                    }).catch((error)=>{

                    })
            },
}

我的控制器在这里...在这里我发现了这个错误

    public function store(Request $request)
    {
        $uploadedFiles = $request->pics;
        foreach ($uploadedFiles as $file) {
            $file->store(public_path('uploads/products'));
        }
        return response()->json(['status'=>'success'],200);
}

status 说 500 错误...在我的网络中我收到了那个错误...并且说为 foreach() 提供的参数无效。

这是我的全部数据..

data: function(){
            return{
                form: new Form({
                    product_name:null,
                    product_color:null,
                    publication_status:1,
                    category_id:'',
                    brand_name:null,
                    product_price_regular:null,
                    product_price_discount:null,
                    product_quantity:1,
                    short_description:null,
                    long_description:null,
                    user_name:'Admin',
                    // product_image:[],
                }),
                attachments:[],
                imageForm : new FormData,
            }
        },  

请看这部分 当我这样做时,其他字段保存在数据库中,但图像不保存...... 如果我不添加这些字段图像将保存在数据库中

addProduct(){
                for(let i=0;i<this.attachments.length;i++){
                this.imageForm.append('product_image[]',this.attachments[i]);
                }
                const data = {
                    'product_image':this.product_image,'product_name':this.product_name,'product_color':this.product_color,'category_id':this.category_id,'product_price_regular':this.product_price_regular,'product_price_discount':this.product_price_discount,'short_description':this.short_description,'long_description':this.long_description,'user_name':this.user_name,'publication_status':this.publication_status
                }
                const config= {
           headers:{
                    "Content-Type": "multipart/form-data"
                   } 
                }
                axios.post('/save-product',data,this.imageForm,config).then((response)=>{
                        toastr.success('Product Info Added Successfully','Success!');
                    }).catch((error)=>{

                    })
            },

【问题讨论】:

    标签: laravel vue.js file laravel-8 laravel-controller


    【解决方案1】:

    第一件事。 axios 参数未正确传递。 Axios 期望第一个参数是路由路径,第二个是表单数据,第三个是标题。因此,只需修改您的 axios 代码,如下所示即可。

     const config= {
               headers:{
                        "Content-Type": "multipart/form-data"
                       } 
            }
        this.imageForm.append('product_name',this.product_name);
        this.imageForm.append('product_color',this.product_color);
    
        axios.post('/save-product',this.imageForm,config).then((response)=>{
                  toastr.success('Product Info Added Successfully','Success!');
                }).catch((error)=>{
    
                })
       
    
    

    我还附上了 laravel 响应图像以表明它工作正常。

    【讨论】:

    • 这很好用...但是如何将目录更改为公共路径???
    • 亲爱的你试过 laravel 的资产功能了吗?例如资产('profiles/image.png')
    • 否。我可以在我的控制器中执行吗?还有一个补充...当我通过FormData提交此表单时 axios.post('/') 做到了。但是当我想通过 v-form 上传其他字段时如何上传它们。
    • 公共函数uploadFile($path,...$files){ $path = ltrim($path,'/'); foreach ($files as $file){ $orginalName = $file->getClientOriginalName(); $newName = time().'_'.$orginalName; $file->move(public_path().'/'.$path,$newName); } } 假设您在公共目录中有文件夹配置文件,然后只需传递文件和路径,如下所示。 uploadFile('profiles',$file);您还可以在第二个参数中传递文件数组
    • 将 v-modal 绑定到输入字段,并在提交表单时用键附加该值。例如 this.imageForm.append('username',this.username)
    猜你喜欢
    • 2022-01-24
    • 2018-12-09
    • 1970-01-01
    • 2015-06-29
    • 2017-02-15
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多