Skip to content Skip to sidebar Skip to footer

How Do I Upload A File Using Node Js?

I have looked around and looked at various tutorials on how to upload a file using node/express. I feel like I am doing something wrong on either the HTML or JQuery side. I am usi

Solution 1:

app.post('/upload', function(req, res) {

    fs.readFile(req.files.image.path, function (err, data) {

        var imageName = req.files.image.name

        /// If there's an error
        if(!imageName){

            console.log("There was an error")
            res.redirect("/");
            res.end();

        } else {

          var newPath = __dirname + "/uploads/fullsize/" + imageName;

          /// write file to uploads/fullsize folder
          fs.writeFile(newPath, data, function (err) {

            /// let's see it
            res.redirect("/uploads/fullsize/" + imageName);

          });
        }
    });
});

Solution 2:

app.post('/', function(req, res) {
  console.log(req.files);
  fs.readFile(req.files.displayImage.path, function (err, data) {

    var newPath = __dirname + "/uploads/"+req.files.displayImage.name;
    fs.writeFile(newPath, data, function (err) {
      if (err) throw err;
      res.redirect("back");
    });
  });
});

Just for your reference, "console.log(req.files)" would contain something like this:

{ displayImage:
   { domain: null,
     _events: null,
     _maxListeners: 10,
     size: 84654,
     path: 'E:\\Users\\xyz\\AppData\\Local\\Temp\\90020831e2b84acb2d4851e4d4
2d77d5',
     name: 'ccc - 1.jpg',
     type: 'image/jpeg',
     hash: false,
     lastModifiedDate: Wed May 22 2013 07:47:39 GMT+0530 (India Standard Time),
     _writeStream:
      { domain: null,
        _events: null,
        _maxListeners: 10,
        path: 'E:\\Users\\xyz\\AppData\\Local\\Temp\\90020831e2b84acb2d4851e
4d42d77d5',
        fd: 4,
        writable: false,
        flags: 'w',
        encoding: 'binary',
        mode: 438,
        bytesWritten: 84654,
        busy: false,
        _queue: [],
        _open: [Function],
        drainable: true },
     length: [Getter],
     filename: [Getter],
     mime: [Getter] }
}

Solution 3:

I ran into the same problem. Sails did not recognize req.files (undefined). So your problem seems very much Sails related. The following solved my problem (especially the Skipper documentation).

In the 0.9 version of Sails, you can uncomment this line in the config/express.js file: // bodyParser: require('express').bodyParser,

In the 0.10 version, use req.file instead of req.files. See their beta documentation on file uploads: http://beta.sailsjs.org/#/documentation/reference/Upgrading

Be sure to check out the Skipper documentation as well: https://github.com/balderdashy/skipper. Most likely your version of Sails will use this to process the file uploads.


Post a Comment for "How Do I Upload A File Using Node Js?"