Hi. I am using react, multer and node.js
I am uploading one image with .single method without any problem. but I can't upload multiple files and I don't get any errors.
I tested back-end node.js code with Postman and it works (it uploads multiple images), but when I try with react, it fails. What I get with req.files is empty array.
Please see my code and help me as soon as possible, because I am going to finish my project very soon.
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
//uploaded files destination
cb(null, "./client/public/images");
},
filename: (req, file, cb) => {
const newFilename = `${new Date().getDate()}-${new Date().getMonth() +
1}-${new Date().getFullYear()}-${file.originalname}`;
cb(null, newFilename);
}
});
const upload = multer({ storage }).array('files');
const Product = require("../../modules/products");
router.post("/addnew", upload, (req, res) => {
let products = JSON.parse( // Saving products database
fs.readFileSync(path.join(__dirname, "../../db") + "/products.json")
);
const product = new Product(req.body, req.files, uuidv4()); // Creating new Product
products.unshift(product); // Adding new product to products array
products = JSON.stringify(products); // Updating products database
fs.writeFileSync(
path.join(__dirname, "../../db") + "/products.json",
products
);
return res.json(product);
});
import React, { Component } from "react";
import axios from "axios";
export default class NewProduct extends Component {
state = {
files: "",
};
onChangeHandler = e => {
this.setState({ files: e.target.files });
};
onSubmitHandler = e => {
e.preventDefault();
let formData = new FormData();
formData.append("files", this.state);
axios
.post("/api/products/addnew", formData)
.then(res => {
})
.catch(err => {
console.log(err);
});
};
render() {
return (
<form className="form-product" encType="multipart/form-data" onSubmit={this.onSubmitHandler} >
<div className="form-row">
<label htmlFor="customFile">Product Images</label>
<div className="custom-file col-md-12">
<input type="file" multiple className="custom-file-input" id="customFile" name="files" onChange={this.onChangeHandler} />
<label className="custom-file-label" htmlFor="customFile">
Choose Main Photo
</label>
</div>
</div>
<div className="col-md-12 text-center">
<button type="submit" className="btn btn-primary new-product-button">
Add
</button>
</div>
</form>
)
}
}
You're essentially doing formData.append('files', { files: [File, File, File] }) which won't work, try reworking it into something like:
for (const file of this.state.files) {
formData.append('file', file)
}
Most helpful comment
You're essentially doing
formData.append('files', { files: [File, File, File] })which won't work, try reworking it into something like: