The usual form on the client:

<form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit" name="button">Отправить файл</button> </form> 

How to handle a file without using express / koa on the server and without AJAX on the client? The main thing that I can not understand is how to get the file name. The file data itself is normal - the file is successfully saved on the server. Using AJAX, everything is sent without problems - both the file itself and its name (we ask ourselves), but it’s interesting how to do this using just HTML5 on the client (as I understand, multipart / form-data was created specifically for this) and processing on the node.

 switch (req.method) { case 'POST': // вместо filename сейчас заглушка из рандомного названия receiveFile(__dirname + '/files/' + 'filename', req, res); break; /* .... */ } function receiveFile(filePath, req, res) { let file = fs.createWriteStream(filePath, {flags: 'wx'}); req.pipe(file); /* .... */ } 

  • You can use some kind of library, for example, multiparty - Save14

1 answer 1

Yes, even with the express, even without the express - anyway, the encoded form must be parsed into fields and files. To do this, take the modifier formidable - and parse:

 http.Server(function(req, res) { if(req.url == '/upfile') { var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files){ if(err) console.error(err); console.log(fields); console.log(files); res.end('thank-you'); }); } else { file.serve(req, res); } }).listen(3000, function() {console.log('PORT: 3000')}); 

The first console will write the fields (finished object, of course), and the second will write data about the sent files, including the way in which he saved the file and what random name (without extension) it has been assigned to - then do with it, they say want to

(But there is a problem. The check for cross-site requests does not take this form - the token does not see it before parsing. I don’t know how to overcome it yet.)

  • What kind of verification is this for "cross-site requests"? :) - JavaRunner