Cannot append to formData object on file upload in React

Viewed 5433

I am new to react and I am attempting to upload a file to my node backend, but I've spent a while at this and cannot get it to work. I appear to send the data correctly to my handle function, but after that I cannot append it to my formData object.

Here is the function that I call on a handle submit button from my upload html.

 uploadAction(){
    var self = this;
    console.log('inside uploadAction');

    var data = new FormData();
    // var filedata = {};
    var filedata = document.querySelector('input[type="file"]').files[0];

    data.append('file', filedata);

    console.log('this is the value of data in uploadAction ', data);
    console.log('this is the value of filedata in uploadAction ', filedata)

    const config = { headers: { 'Content-Type': 'multipart/form-data' } };
     axios.post('http://localhost:5000/upload',{
       filedata: data
     },config)
       .then((response)=>{
         console.log('back again success from upload');
       })
       .catch((err)=>{
         console.error('error from upload ', err);
       });

So when I console log out the data and the filedata objects I get the following result.

this is the value of data in uploadAction  FormData {}

this is the value of filedata in uploadAction  File {name: "suck.jpg"....

So somehow it appears that my filedata is being brought in correctly, but there's a disconnect on how this being appended to the data object. Which I find confusing, as this seems to be the way I've found to append this data object from looking at these things online. I think my axios call is correct, but I am of course getting to an error before that.

Does anyone have any suggestions on how I can fix this? Is there an easier way to do this in react that doesn't involve using querySelector? I probably don't want to use dropzone or a similar library/package, I just want to learn how to do a simple upload file.

If anyone has any suggestions on this I would really appreciate it. I've spent some time on this and I seem to be going in circles.

EDIT: as per the suggestion of the first comment below I have added

for (var pair of data.entries()) {
  console.log(pair[0]+ ', ' + pair[1]);
}

to my code to try and console log my data value (ie the dataForm object). The result was:

file, [object File]

while this is true, it doesn't help fix my problem.

1 Answers
Related