MathankumarK
MathankumarK

Reputation: 2905

File not uploaded using node js multer

I am new to develop Rest API, I have tried this below methods to upload a file using HTML this code works. Then I tried this in postman I got positive response but file wasn't uploaded, May I know what I have done wrong?

    var express     =   require("express");
    var app         =   express();
    var multer  = require('multer')

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now()+".jpg");
  }
});

var upload = multer({ storage : storage}).single('userPhoto');

I used this below method to upload a file. It's worked when I upload a file using HTML. But If I tried this using postman I got file is uploaded message. But in the destination folder there is no file.

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        if(err) {   
        //  res.end({"error" : true,"message" : "Error uploading file."});
        res.end("Error uploading file.");
        }
    res.end("File is uploaded");
        // res.json({"error" : false,"message" : "File is uploaded"});
    });
});

Here I have added my HTML file

<html>
  <head>
    <title>File upload Node.</title>
  </head>
  <body>
      <form id="uploadForm"
          enctype="multipart/form-data"
          action="/api/photo"
          method="post">
      <input type="file" name="userPhoto" />
      <input type="submit" value="Upload Image" name="submit">
      <span id = "status"></span>
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
  <script>
  $(document).ready(function() {

     $('#uploadForm').submit(function() {
         $("#status").empty().text("File is uploading...");

        $(this).ajaxSubmit({

            error: function(xhr) {
                    status('Error: ' + xhr.status);
            },

            success: function(response) {
                    console.log(response)
                    $("#status").empty().text(response);
            }
    });

    return false;
    });    
});
  </script>
</html>

I tried many ways but I can't find any solution, Can anyone please help me to fix this issue?

Upvotes: 0

Views: 758

Answers (1)

MathankumarK
MathankumarK

Reputation: 2905

Code working good, Issue happened because of the request header.

{"Content-Type":"application/json"}

I just removed it.

This answer helped me to fix this issue

Upvotes: 1

Related Questions