3

I want to send PDF/Docs files in axios service along with other JSON data. I have refered (Ajax post a file from a form with Axios) but it only sends file without any JSON data.

 field_value: {}, // here it shows empty object,but it should show File Object
 field_type: "file_upload", 
 is_file_upload: true

}

when I console the object before sending request than it shows me a file object in FormData() but it show empty braces when is see it in post request.

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

You can do something like this:

//HTML    
<input type="file" @change="onFileChanged" :multiple="multiple" :accept="accept" />

Then your javascript code to handle the file input:

onFileChanged(event) {
  var files = event.target.files || event.dataTransfer.files;
  if (!files.length) {
    return;
  }

  var formData = new FormData();

  // Add the File object to the formdata
  if (this.multiple) {
    formData.append("files", files);
  } else {
    formData.append("file", files[0]);
  }

  // Add your data...
  formData.append("data", myData);
}

uploadDocument(formData) {
  return Axios.post('/api/documents', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

Use the formData which you get from file input type to send to the backend.

Then you can do something like this:

uploadDocument(formData).then((response) => {
  console.log('data sent');
})  

Hope it helps.

V. Sambor
  • 12,361
  • 6
  • 46
  • 65