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?
Well ,When you upload files with multer
the uploaded file data is not stored directly in req.body
, rather multer
attach file-data
into request.file
(for single file) & request.files
(for multiple/arrays of file).
request.body
contains onlye the text-fields
.
So try this code in place of your existing code.
app.post('/addPost', upload.single('blogImage'), (req, res) => {
let fileData = req.file ;
if(!fileData) //return `true` in case file is not submitted
{
..... //you can redirect user or whatever you want
}
.....
//you can do rest of the work regarding file-upload
});
For more information on multer
you can visit the link below.