Steal1702
Steal1702

Reputation: 123

Unable to upload a file using Vue frontend and laravel server

I am trying to upload a file (File can be anything i.e. an image or pdf or doc, absolutely anything) . For that, I made a test form into my Vue component that is below

<form class="mt-5" method="post" enctype="multipart/form-data" id="uploadForm">
        <div class="form-group">
            <input type="file" id="test" name="test" class="form-control">
        </div>
        <button @click.prevent="uploadFile" type="button" class="btn btn-sm btn-primary">Upload</button>
</form>

Now when I submit form (click the upload button), I am running a function below

uploadFile() {
                let something = $('#test').prop('files')[0];
                console.log(something);
                let form_data = new FormData();
                form_data.append('file', something);
                console.log(form_data);
                axios.post('/upload/file', { form_data })
                    .then(() => {
                        console.log("done");
                    })
            },

So when I console.log(something), it shows me the info of uploaded file but when I send data to server using axios and dd($request->all()) there, it shows me something => [] an empty array, that means, I am not getting the file and hence cant process it further to save it into my folders (upload).

What am I doing wrong here?

Upvotes: 0

Views: 719

Answers (1)

Lucas Silva
Lucas Silva

Reputation: 1411

This happens because you are not setting the header Content-Type as multipart/form-data (and by default the application/json is being used) when making the request with axios, and the enctype attribute has no effect, since your not using the default form submit action. So try to pass a third argument in the post method, specifying the correct Content-Type header.

const uploadAvatar = ({ id, file }) => {
  const formData = new FormData();

  formData.append('avatar', file);

  return axios.post(`users/${id}/avatar`, formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
};

Upvotes: 2

Related Questions