H
H
Halyluya2015-08-16 00:08:15
JavaScript
Halyluya, 2015-08-16 00:08:15

How to parse FormData request in nodejs?

Again, we need the help of the community, I myself have already reached a dead end.
The bottom line is, files are uploaded from the site to the server (pictures), the server chews them up, does something and saves somewhere there, it doesn’t matter. All code is "lightweight" without checks, simplified for clarity.
Client side code:

// ткнули в input, выбрали файл и сработало событие 'change'
    var files = event.target.files;  // получили FileList

   for (var i = 0; i < files.length; i++) {
  var file = files[i];
    
  // оформляем отправку данных
  var form = new FormData();
  form.append("name", file.name);
  form.append("size", file.size);
  form.append("file", file);

         // отсылаем на сервер
  var XHR = new XMLHttpRequest();
  XHR.open('POST', '/image?toAdd', true);
  XHR.send(form);	
};

the code is simple, everything seems to be fine, the browser itself adds headers and it all goes to the server.
Now the receiving code (also simplified).
// запрос дошел до адресата и код пришел в виде обьектов Buffer по 63кб кажется
var fullbody = "";
request.on('data', function (chunk) {
  fullbody += chunk; // склеиваем его в один
});
request.on('end', function () {
  var decodedBody = querystring.parse(fullbody); // пробуем распарсить	
});

and a bummer, not parsed, or rather parsed, but it turns out an object
{
 null : "error while processing request '{_request}' (exception: {_exception})"
}

Well, actually the question is, how to parse it correctly? The code has already been simplified, there is nowhere else, what the trouble is - I can’t understand. And yes, I am writing without Expressa and third-party modules, I would like to solve and understand the problem.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2015-08-16
@halyluya

When parsing MIME, and this is not a simple format, it will not be a sin if you take the https://www.npmjs.com/package/multiparty module and apply it only if the content-type exactly contains MIME

var contentType = req.headers['content-type'];
if (contentType && contentType.indexOf('multipart') === 0) {
  var form = multiparty.Form();
  form.parse(req, function(err, fields, files) {
    if (!err) {
      // тут имеем files
    }
  });
}

Blessed are those who write without Expressa

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question