This is the app.post method in the index.js file which will receive the filename and I want to check if the image exists then the image name will be added to the file else it will not.
app.post('/addPost', upload.single('blogImage'), (req, res) => {
//for the written content
let data = req.body;
data.blogImageName = req.file.filename;
console.log(data);
postContent(req.body);
});
This is the html form
<form action="/addPost" enctype="multipart/form-data" method="POST" class="createPostForm">
<div>
<label for="AddImage">Add Image for the blog : </label>
<input type="file" name="blogImage" ><br>
</div>
<input type="submit" value="Add Post">
</form>
if i submit the form without uploading file then it gives an error.
How can i check if filename exists in the request?
2
Answers
add validation
Well ,When you upload files with
multer
the uploaded file data is not stored directly inreq.body
, rathermulter
attachfile-data
intorequest.file
(for single file) &request.files
(for multiple/arrays of file).request.body
contains onlye thetext-fields
.So try this code in place of your existing code.
For more information on
multer
you can visit the link below.https://www.npmjs.com/package/multer