S. A. Malik
S. A. Malik

Reputation: 3665

Save POST data to local server using NodeJS

Using nodeJs with express.

The POST data is being parsed by body parser. Now i want to save the received image file in a folder of express application named images. The image is being posted to nodeJs app. When i look at the res.body variable in the callback function it contains the image, but i am confused how to save it.

I have looked on stackflow but could not find any answer. So posted myself.

I have tried using the fs library and its fs.writeFile() function. It saves the file but it is all corrupted.

image1 is the name of image in posted data. Using bodyparser()

var image = req.body.image1;
        fs.writeFile('images/newImage.jpg', image, function(err){
            if (err) throw err;
            console.log('It is saved');
        });

This saves a file in images directory but it is not the image.

I am using curl to post data to the nodejs application, the code is

$curl = curl_init();
$data = array('name' => 'First','file' => "image1=@".__dir__."/images/1.jpg");

curl_setopt($curl, CURLOPT_URL, "http://localhost:3000/api/");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_exec($curl);
curl_close($curl);

I am logging both of the two console.log functions

   console.log(req.files);
   console.log(req.body);

and the log give

{}
{ name: 'First',
  file: 'image1=@C:\\xampp\\htdocs\\curltest/images/1.jpg' }

Please help this is driving me crazy :-/

Upvotes: 0

Views: 12548

Answers (2)

rubelux
rubelux

Reputation: 61

if you are using Express 4, bodyParser is not included, but what you really need is to use a multiparty package, I use this and your code will be something like this:

within your POST router

var form = new multiparty.Form();

form.parse(req, function(err, fields, files) {
        if(err){
            res.status(500).send('not file');
        }
     res.send(util.inspect({fields: fields, files: files}));
});

hope this helps

Upvotes: 0

KARASZI István
KARASZI István

Reputation: 31467

First of all the correct parameter order of fs.writeFile is the filename first then the content.

If you're using express.bodyParser() you'll have the uploaded files in the req.files field.

And of course you should write the callback:

fs.writeFile('newImage', req.files.image, function (err) {
  if (err) throw err;
  console.log("It's saved");
});

Update

You should also check your HTML side, because the encoding of your form must be multipart/form-data.

Example:

<form action="/somewhere/to/post" method="post" enctype="multipart/form-data">
  <input type="file" name="image1"/>
  <input type="submit"/>
</form>

Upvotes: 2

Related Questions