So the thing is I am making a form that will save the name and image path of an object in the database. Additionally, I need to save the images in my directory so I can retrieve them later on. Where can I add, in this case, a new api call to "http://localhost:5000/products"?
return (
<>
<form
className="modal-container"
action="http://localhost:5000/upload"
method="post"
enctype="multipart/form-data"
>
<div className="modal-box">
<input
type="text"
placeholder="Name of the product"
className="btn-input-text"
name="product-name"
onChange={(e) => setName(e.target.value)}
></input>
<input
type="file"
accept="image/*"
className="btn-input-image"
name="product-image"
onChange={(e) => setImage(e.target.value)}
></input>
<input type="submit" value="submit" />
<span className="btn-close" onClick={onClose}></span>
</div>
</form>
</>
);
Add a product:
app.post("/products", async (req, res) => {
try {
const { name, description, image } = req.body;
const newProduct = await pool.query(
"INSERT INTO products (product_name, product_description, product_image) VALUES ($1, $2, $3) RETURNING *",
[name, description, image]
);
res.json(newProduct.rows[0]);
} catch (err) {
console.error(err.message);
}
});
Save the image in my directory (using multer):
app.post("/upload", upload.single("product-image"), async (req, res) => {
console.log(req.file);
res.send("Image Uploaded");
});
Thank you !
CodePudding user response:
With React you can bypass the default behaviour of a form submitting data with a POST request to one API Endpoint and write your own handleSubmit function that uses two APIs instead.
CodePudding user response:
You can do both jobs with one api call. Your image is saved in directory via the upload middleware.
You can access details of file inside post route by req.file
and content of other fields by req.body
.
You can merge post routes into one upload route. You will also be able to save file details in the database which you can use to retrieve file later. E.g rq.file.originalname
app.post("/upload", upload.single("product-image"), async (req, res) => {
const { name, description} = req.body;
const image = req.file.originalname;
const newProduct = await pool.query(
"INSERT INTO products (product_name, product_description, product_image) VALUES ($1, $2, $3) RETURNING *",
[name, description, image]
);
console.log(req.file);
res.send("Image Uploaded");
});