The simplest way to do this is through the "Connect-multiparty" middleware for uploading.
Install by using NPM install Connect-multiparty in your project.
Usage:
var multipart = require (' Connect-multiparty '); var multipartmiddleware = multipart (); App.post (function(req, resp) { Console.log (Req.body, req.files); // });
After uploading, the uploaded file will generate a temporary file in the temporary directory, specifically to print out the req.files to view the specific file path.
Upload is done as long as the temporary files are moved and renamed to the actual directory where they are commented.
Simple.
Official address: Https://www.npmjs.com/package/connect-multiparty
However, the official does not recommend the use of the middleware, it is recommended to use "multiparty", because error handling is more troublesome.
The following is a version implemented with "multiparty".
1. Use Express (version 4.11.x) to create a project that uses the default jade as the template engine.
2. In the project directory, install the necessary components via NPM install multiparty.
3. Modify the Views/index.jade to do a simple form for file upload.
1 extends Layout 2 3 block content 4 form (method= ' post ', action= '/file/uploading ' , enctype= ' Multipart/form-data ') 5 input (name= ' inputfile ', type= ' file ', multiple= ' mutiple ') 6 input (name= ' btnup ', type= ' submit ', value= ' upload ')
4. Modify the Routes/index.js, implement the download page and download the background code.
1varExpress = require (' Express '); 2varRouter =Express. Router (); 3varMultiparty = require (' multiparty ')); 4varUtil = require (' util ')); 5varFS = require (' FS '); 6 7/*download Page*/8 Router.get ('/',function(req, res, next) {9 Res.render (' index ', {title: ' Express ' }); 10 }); 11 12/*Download*/Router.post ('/file/uploading ',function(req, res, next) {14//build the Multiparty object and configure the download destination path15varform =NewMultiparty. Form ({uploaddir: './public/files/')}); 16//post-Download processingForm.parse (req,function(Err, fields, files) {18varfilestmp = json.stringify (Files,NULL, 2); 19 20if(err) {Console.log (' Parse error: ' +err); 22}Else { Console.log (' Parse files: ' +filestmp); 24varInputfile = files.inputfile[0]; 25varUploadedpath =Inputfile.path;26varDstpath = './public/files/' +Inputfile.originalfilename;27//Rename to real file nameFs.rename (Uploadedpath, Dstpath,function(err) {29if(err) {Console.log (' Rename error: ' +err); 31}Else { Console.log (' Rename ok '); 33 } 34 }); 35 } Res.writehead ($, {' Content-type ': ' Text/plain;charset=utf-8 ')}); Res.write (' Received upload:\n\n '); 39Res.end (Util.inspect ({fields:fields, files:filestmp}));40 }); 41 }); Module.exports = router;
Complete.
The usage of "multiparty" is described in:
Www.npmjs.com/package/multiparty
Github.com/andrewrk/node-multiparty
Using Nodejs+express (4.x+) for file uploads