I have an uploader that allows a user to upload several pictures. In order to only create or update the images he wants to add/change, I update an object that looks like this:
{main: Blob, "1": Blob, "2":Blob}
So if only needs to update "1" later, the sent object will only contain
{"1": Blob}
When clicking on save, it triggers a function that is supposed to append the images to a formData(). Sadly the formData is never updated. I have the following error:
Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.
export async function uploadImages(files, userId) {
try {
const images = new FormData();
files.main && images.append("image", files.main, "main");
files[1] && images.append("image", files[1], "1");
files[2] && images.append("image", files[2], "2");
const res = await ax.post(process.env.SERVER_URL + "/upload-images", {
images,
userId,
});
return "success"
} catch (err) {
return "error"
}
}
How to fix this? Thanks!
You should not be able to see FormData object contents in console, because its not serializable. You can check request payload instead, check "Network" tab in your browser dev tools, find your request and look at the bottom of "Headers" tab to see "FormData" log. You will see something like this:
Also, you should set header "Content-Type" to "multipart/form-data" in axios. Here is working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<input type="file" multiple id="filepicker" />
<button id="send">Send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<script>
const myformData = new FormData();
document
.querySelector('#filepicker')
.addEventListener('change', function (event) {
const { files } = event.target;
Object.values(files).forEach(function (file, index) {
myformData.append(index, file);
});
});
document.querySelector('#send').addEventListener('click', function () {
axios({
method: 'post',
url: 'http://google.com',
data: myformData,
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
});
</script>
</body>
</html>