Search code examples
vuejs3vue-componentlaravel-10

Send a file in an axios request to api, with vue component - why is it *empty*?


In my vue component, I have a form.

There's this field in it: <input type="file" name="image" id="image" class="form-control" required ref="image">

When I log this.$refs.image.files[0] it returns this

File {name: 'random-image.jpg', lastModified: 1684076710626, webkitRelativePath: '', size: 983632, …}

But when the Axios post request is sent, the payload is image:{}, so the image is not really sent.

I'm trying to submit the file/image to the API, am I missing something?

If the provided code snippet returns the data of the image, why is it not being sent to the API?

I've tried answers from other questions, but those didn't solve the problem. I know I'm forgetting something, but can't figure out what.

Edit 1: So when I do this

async submitForm(){
            let formData = new FormData();
            formData.append('image', this.$refs.image.files[0]);
            formData.append('name', this.name);
            formData.append('price', this.price);
            let response = await submitProductForm(formData)

It actually works. But what's the difference between using a FormData, and not using one? Now in the payload, the image is a binary, not a file.


Solution

  • enctype="multipart/form-data" I believe this solved the problem. Not sure since it's quite old question.