2

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?

6
  • 1
    did you want to check on the server or in the client, it's not clear from your question Commented Jun 17 at 11:04
  • To upload a file you need multer or express-fileupload package. Do you only want to know how to check if user submitted file or you want to know the entire process about how to check and upload file as well?Please specify
    – Subha
    Commented Jun 17 at 11:16
  • I wanted to check on the server side @JaromandaX Commented Jun 17 at 15:21
  • I have imported the multer package. I want to check at the server side if the user has submitted image or not. @Subha Commented Jun 17 at 15:24
  • @VedicaGairola, I have posted my detailed answer with explaination.Please chcek and let me know your feedback.
    – Subha
    Commented Jun 17 at 16:44

2 Answers 2

1

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.

https://www.npmjs.com/package/multer

0
1

add validation

if (!req.file) { throw new Error("File is required"); }
return true;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.