Rahul
Rahul

Reputation: 314

Express JS Save image on server

I am sending image from my iPhone App to server. Restful API is in express JS. I am getting image on server using POST request. I am able to print the binary data but not able to store it properly. When I open the image from specified location,its corrupted. Here is my express js code.

app.post('/api/pictures',function(req,res){
console.log(req.headers);
    var body = '';
    filePath = 'C:/Users/Desktop/restful/image.png';
    req.on('data', function(data) {
    console.log(data);
    body += data;
});

 req.on('end', function (){ 
     fs.appendFile(filePath, body, function() { 
     res.end(); 
     });
   });
  res.send("Success!");
});

My req.headers is

enter image description here

Am I doing anything wrong?

Where as I am getting this response on client side

{ status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 8;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 14 Jan 2015 16:15:01 GMT";
"X-Powered-By" = Express;
 } }
upload completed, response: Optional(Success!)

Thanks in advance.

Upvotes: 0

Views: 4207

Answers (2)

Rahul
Rahul

Reputation: 314

Finally I am able to upload image using connect-multiparty.

app.post('/api/uploadimage', multipartMiddleware, function(req, res) {
 console.log(req.body, req.files); // check console 

fs.readFile(req.files.urForm-data_name.path, function (err, data) {
       fs.writeFile(newPath, data, function (err) {
      });
    });
 });

Upvotes: 1

mscdex
mscdex

Reputation: 106696

You need to use a multipart-parsing middleware such as multer, multiparty, formidable, or connect-busboy.

Upvotes: 0

Related Questions