0
votes

I am facing issues when trying to process an uploaded picture and write it into a file. Usually this work very well that way:

req.on('data', function (data) {
  body += data;
  wstream.write(data);
});
// end process data
req.on('end', function () {
  wstream.end();
});

In that case written file header looks like that:

PNG ... followed by binary data.

But in some cases written file looks like that:

--72e245e8-38eb-41e8-9118-fc0405e4837c Content-Type: multipart/form-data Content-Disposition: form-data; name=image; filename=picture.jpg; filename*=utf-8''picture.jpg

As you can imagine, those pictures arent working well anymore until I remove that meta data as content-type etc.

But after I do so, picture is fully functional and useable.

I tried to access the request data and called toString Method to replace the "unwanted" parts, but than I entirely mess up content encoding of that output file and it becomes unuseable at all.

data = data.toString(/---.*/g), "");

Any ideas how to do the trick?

1
Use something like body-parser? github.com/expressjs/body-parser - Krishna Kalubandi
Thanks for your reply. It seems that expecially that thing is not made for this. Hence that module says: This does not handle multipart bodies. But they are hinting to other modules as formidable. - Chris

1 Answers

0
votes

I solved my issue by help of module formidable.

var formidable = require('formidable');
var util = require('util');

form.parse(req, function(err, fields, files) {

    logger.debug("Received upload: " + util.inspect({fields: fields, files: files}));

});


form.on('fileBegin', function (name, file){

    file.path = "MyPathToDestinationFile";

    logger.debug("File  upload started for file '" + file.path + "'");

});


form.on('end', function() {

    logger.debug("File upload finished for file");

    // Send response to client

});


form.on('error', function(err) {

    logger.debug("Failed to finish upload due to '" + err + "'");

    // Send error to client

});