laracasts / Vue-Forms

https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19
396 stars 204 forks source link

Uploading file(s) with form. #25

Open bdjunayed opened 4 years ago

bdjunayed commented 4 years ago

I am trying to send a file with these modification but received an empty array [] from the controller with dd(). Could anybody can show me the way to do it.

Form.js

   submit(requestType, url) {
        let config = {
            headers: {
                'Content-Type': `multipart/form-data; boundary=${Math.random().toString().substr(2)}`,
            }
        }
        return new Promise((resolve, reject) => {
            axios[requestType](url, this.data(), config)
                .then(response => {
                    this.onSuccess(response.data);

                    resolve(response.data);
                })
                .catch(error => {
                    this.onFail(error.response.data.errors);
                    reject(error.response.data);
                });
        });
}

ExampleComponent.vue

<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
        methods: {
            onSubmit() {            
            this.form.post('/candidates')
                .then(response => {
                    this.response = response          
                })
                .catch((err) => {
                })
            },
            handleFileUpload(){
                this.form.file2 = this.$refs.file.files[0];
            }
        }, 
mnikzad commented 4 years ago

you should do it with FormData:

/**
 * Fetch all relevant data for the form.
 */
data() {
    let data = new FormData();

    for (let property in this.originalData) {
        this.appendData(property,this[property],data);
    }

    return data;
}

 appendData(key,value,appendTo){
    if (value instanceof Array){
        for (const i of value.keys() ){
            this.appendData(`${key}[${i}]`,value[i],appendTo)
        }
    }
    else if (typeof value === "object"
    && value !== null
    && !(value instanceof File))
    {
        for (const k in value) {
            if (value.hasOwnProperty(k)) {
                this.appendData(`${key}[${k}]`,value[k],appendTo);
            }
        }
    }
    else {
        appendTo.append(key,value)
    }
 }
iwasherefirst2 commented 4 years ago

You need to use a FormData object if you want to send files. Checkout my pull request: https://github.com/laracasts/Vue-Forms/pull/27/files or check my video where I explain how FormData works: https://www.youtube.com/watch?v=kEy7w3KAtlc&t=445s