Not able to upload file using react js through Springboot API

28 Views Asked by At

I am trying to upload list of files simultaneously but not able to do it. I get an error that file is not found, although file object is present but in the request it shows that it is an [object Object], although it should be a file binary.

That's how my code is

data.forEach(element => {
    var formData = new FormData();
    data.actualFiles.forEach(
        file => {
            if (file.fileName === element.attachmentUIDTO.fileName) {
                formData.append('file', file);
            }
        }
    )
    
    const resUpload = api.post(`${serviceEnpoints.PRFS_UPLOAD}`, formData);
}

The main issue is happening when I am iterating it in list. I am not sure what I am doing wrong here.

1

There are 1 best solutions below

0
user1880531 On

Make sure you set the request "Content-Type" to "multipart/form-data"

In Axios you can do it like this:

const response = await axios({
        method: "post",
        url: endpoint,
        headers: {"Content-Type": "multipart/form-data"},
        params: {},
        data: formData
      });

And since you are sending several files, I would recommend using the array notation when calling the append method.

Like this:

...

formData.append('files[]', file);

...