0

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?

1 Answer 1

2

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' },
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.