'Uploading images and text using formData in React
I am trying to upload images and text using FormData from other inputs to a server using Axios with the help of an API. I manage to successfully upload all the other fields but my image file does not post in the database.
Here is my code
const changeHandler = (event) => {
console.log(event.target.files);
const [file] = event.target.files;
setImageInfo(URL.createObjectURL(file));
setImage(event.target.files[0]);
setIsFilePicked(true);
};
const handleAddNewProduct = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("vendor", vendor);
formData.append("category", category);
formData.append("name", name);
formData.append("image", image);
formData.append("description", description);
formData.append("quantity", quantity);
formData.append("currency", currency);
formData.append("price", price);
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${vendorToken}`,
};
axios
.post(`${api}/products/product`, formData, {
headers,
})
.then((response) => {
navigate("/vendor/Shop");
})
.catch((error) => setError(error.response.message));
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
