React axios multiple files upload
Here is a full working set up (expanded version of the answer above)
Client side:
// silly note but make sure you're constructing files for these (if you're recording audio or video yourself)// if you send it something other than file it will fail silently with this set-up let arrayOfYourFiles=[image, audio, video]// create formData objectconst formData = new FormData();arrayOfYourFiles.forEach(file=>{ formData.append("arrayOfFilesName", file);});axios({ method: "POST", url: serverUrl + "/multiplefiles", data: formData, headers: { "Content-Type": "multipart/form-data" }})//some error handling
Server side (express, node - mutler)
const UPLOAD_FILES_DIR = "./uploads";const storage = multer.diskStorage({ destination(req, file, cb) { cb(null, UPLOAD_FILES_DIR); },// in case you want to change the names of your files) filename(req, file = {}, cb) { file.mimetype = "audio/webm"; // console.log(req) const {originalname} = file; const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0]; cb(null, `${file.fieldname}${Date.now()}${fileExtension}`); }});const upload = multer({storage});// post route that will be hit by your client (the name of the array has to match)app.post("/multiplefiles", upload.array('arrayOfFilesName', 5), function (req, res) { console.log(req.files, 'files') //logs 3 files that have been sent from the client}
This is not the right way to generate keys. You can try something like this:
let productimages = [];for (let i = 0; i < images.length; i++) { productimages.push(images[i]);}formData.append('productPhotos', productimages);