I want to upload several images to my nodejs server that have additional information such as title and category , I tried sending the images in DataUrl but due to POST limitations it does not allow me to upload more than 2 images at a time.
To upload the images I use this reactjs component Image Upload Component which has the handleSubmitImages method to send the component state to the server via ajax.
handleSubmitImages()
handleSubmitImages(){
let xhr = new XMLHttpRequest()
let json = JSON.stringify({images: this.state.images})
xhr.open("POST",'new',true)
xhr.setRequestHeader("Content-Type","application/json")
xhr.send(json)
}
Component Status
The state of the component is formed by an array of json objects that contain the information of the images as follows:
[
{ title: 'Imagen 264',
file: [Blob], // Este es el blob del archivo
data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA', //Imagen en base64
category: 1 }
]
On the server I have the wallpapers/new route to upload images using the POST method .
Route wallpapers/new
router.route("/new")
.get(function(req,res){
res.render('wallpaper/new',{
user: req.user
})
})
.post(function(req, res) {
let images = req.body.images
images.map(image => {
// Aquí debería poder guardar la imagen en mi servidor
})
});
NOTE: I have read tutorials that make use of formidable and FormData() to upload several images at the same time, but in none of them do they send additional information such as the title of the image or something similar. I hope you can help me.
It is not necessary to send the image 2 times, I recommend that you only send the
data url
and forget to send the Blob, you cannot serialize it in a json, if you choose this way, (as far as I know) you can only useFromData
which is an alternative method .To send multiple images, you can solve it very easily by moving the loop to the client side. So the server's transfer limit will be applied to each image ( minus ~1/3 overhead ) and not to the entire collection of images. You also make better use of the bandwidth by sending several images at the same time.
Then on the server side you only receive the files one by one: