edoc's avatar
Level 24

Vue ajax file upload

Hi. I am trying to upload a file using vue.js,

The code below works as it's supposed to, but I am wondering if I am missing something else.

Please let me know if there is a better way or more secure way to do this.

<input type="file" ref="file" @change="uploadFile" name="file">

methods: {
        uploadFile () {
            let data = new FormData;

            data.append('file', this.$refs.file.files[0]);

            if(this.$refs.file.files.length > 0) {
                axios.post(this.url, data)
                    .then( (response) => {
                        console.log(response)
                    })
            }
        }
    },
0 likes
2 replies
bunnypro's avatar
bunnypro
Best Answer
Level 7

i think you can move the file checking in the beginning

if (! (this.$refs.file.files.length > 0)) {
    return;
}

so it doesn't have to do all things that unnecessary.

mike_hasarms's avatar

Will this upload the file as soon as the user selects it, before they submit the form?

If so they might be sending the wrong file by mistake (due to a mis-click) with no chance to correct before you've received their file. As a user I wouldn't like that

Please or to participate in this conversation.