rekha s rekha s - 5 months ago 4
Node.js Question

Node Js Image Upload Not working

I need to upload the image to server using node js.The image is coming from ios app as a file data. I have used the following code,

var fs = require("fs");
var imageName = req.files.profile_image.name;
fs.readFile(req.files.profile_image.path, function (err, data) {
console.log(imageName);
// If there's an error
if(!imageName){
console.log("There was an error")
//res.redirect("/");
//res.end();
} else {
console.log(data);
var newPath = 'http://example.com/images/' + imageName;
// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
// let's see it
console.log(err);
//res.redirect("http://example.com/images/" + imageName);
});
}
});


When I run this code, I have received no error but the image is not uploaded in images folder.

I am getting the following error with fs.writeFile,

{ Error: ENOENT: no such file or directory, open 'http://example.com/images/user-profile.jpg'
at Error (native)
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'http://example.com/images/user-profile.jpg' }


Please help.

Answer

You cannot write the image you are receiving as an url ...
It should be a local path on the server that is running your application.

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

Also do not re-write the image into its new path, but instead move it (with rename()):

fs.readFile(req.files.displayImage.path, function (err, data) {
  // ...
  var newPath = __dirname + "/uploads/uploadedFileName";

  fs.rename(files.upload.path, _path +'/'+ img_name + '.png', function (error) {
    res.redirect("back");
  });
});
Comments