Hello i’ve been working in a blog to post blogs, you can add images too
For add image system i use Multer and Path.
To save the image, I save it in a FormData, with its key, so Multer can read the FormData key when making the POST request
But here is the problem. When i post a blog, i add the name, the post body, and the image saved in a formdata, everything saved in an array that is later sent to the backend with axios
So the formdata is saved into a array of objects
My question is how Multer, can read the formdata stored in the array
Here is the code i use for image and post
Function to post the blog:
const [file, setFile] = useState(); //file is the image submited by the input file
const formdata = new FormData(); //the formdata
const params = useParams()
const handleFile = (e) => {
setFile(e.target.files[0])
}
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await createBlogRequest(targeted) //here I invoke the axios function
console.log(response)
} catch (error) {
console.error(error)
}
setNewUser('')
setNewPost('')
}
formdata.append('image', file)
const targeted = {name: newUser, post: newPost, image: formdata} //here is the array with the parts of the blog
The axios function:
export const createBlogRequest = async (blog) =>{
await axios.post('http://localhost:4000/blogs', blog)
}
The multer and routes functions
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './server/images')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "_" + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage
})
router.post('/blogs',upload.single('image'), createBlog)
//my question is here, how multer when upload.single('image') can read the formdata inside the array
I hope understand because I don’t speak English.
Any response will be welcome
mini1012 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.