ekpono's avatar
Level 12

Attaching multiple image to form

I have a table that contains image fields to be uploaded. obviously, it is only the url that is to be stored in the database while the main image will be sent to amazon s3. The issue is only one image is sent, so am guessing there is a mistake in my loop.

            this.isLoading = true;
            let data = {
                items: this.vendorTableRows,
            };
            for (let i = 0; i < data.items.length; i++) {
                let handle = document.querySelector('.image').files[i];
                    let formData = new FormData();
                    formData.append('file', handle);
                    axios.post('/client/vendor/uploadVendorImage', formData).then(res => {
                        this.vendorTableRows.image = res.data.data
                    });
            }

the data {} object is the object that contains my form object. the data object should contain all the image links not just only one (last one) Here is my html

                                </td>
                                <td><input type="file" class="form-control image" id="image">
                                </td>
                                <td id="delete" @click='deleteVendorRow(index)'><i class="fa fa-trash-o" style="font-size:24px"></i></td>
                            </tr>```
0 likes
1 reply
ekrist1's avatar

hi.

Here is my Vue method which I use to upload multiple files (I´m using loadash to loop through the files). You need to add "multiple" to your input field.

 attachDocuments: function(e) {
            this.fileNames = []
            this.form.attachments =  e.target.files || e.dataTransfer.files

            _.forEach(this.form.attachments, (file) => {
                this.fileNames.push(file.name)
                if(file.size > 15728640) {
                    alert('Filen er for stor. Maks størrelse er 15MB!')
                    this.form.attachments = []
                    this.fileNames = []
                }
            })
            this.submitForm()
        },
        submitForm() {
            this.loading = true
            this.form[this.method](this.action)
                .then(response => {
                    this.loading = false
                    window.location.href = response.redirect
                })
                .catch(error => {
                    this.loading = false
                    if (error.response.status === 401) {
                        this.showmodal('image-auth-error')
                    }
                    this.displayErrorMessage(this.form.errors.all())
                })
        },

input

<input class="cursor-pointer absolute block opacity-0 pin-r pin-t" type="file" name="file" id="file" @change="attachDocuments" multiple accept='image/*'>

Please or to participate in this conversation.