this article illustrates the method of nodejs uploading file based on express. To share with you for reference, it is as follows:

used nodejs server to upload files while doing personal projects some time ago. Now let's summarize this summary as a record.

uploaded files is based on express multiparty", of course, can also be implemented using connect-multiparty middleware, but the official does not seem to recommend the use of "nofollow middleware". Don't say much of the nonsense. Let's look at the code below.


(1) uses express to create projects, and the default use is jade template engine, but it is still used to HTML, so it changes to HTML template.
(2) installs the necessary components through the NPM install multiparty in the project directory.
(3) modifies the views/index.html, adding a file uploaded form.


 < DOCTYPE html> < HTML! Lang= "en" > < head> < meta charset= "UTF-8" > < title> < /title> < file;; /head> < body> < form method='post'file; action='/file/uploading', < input, enctype='multipart/form-data'> type= "file" name= "inputFile" > < input; type= "submit" value= > < "Upload"; /form> /body> < < 

; /html>

(4) to modify routes/index.js, upload page and upload response code.

 var ('express') express = require; VAR = express.Router (router); VAR multiparty = require ('multiparty'); VAR util = require ('util'); VAR FS = require ('fs'); / * * / router.get upload page. ('/', function (req, res, next) {//res.render ('./views/index'); res.sendfile ('./views/index.html');}); / * * / ('/file/uploading', function upload (req, res, next) {/ * and generate a multiparty object, the target path configuration upload / var form = new (multiparty.Form); / * * / form.encoding ='utf-8' edit settings; / / set file storage Road King form.uploadDir ='./public/files'; / / set file the size limit of form.maxFilesSize = 2 * 1024 * 1024; / / form.maxFields = 1000; / / small sum / / set all file upload form.p postprocessing Arse (req, function (err, fields, files) {var filesTemp = JSON.stringify (files, null, 2); if (ERR) {console.log ('parse error:'+ err;}else) {console.log ('parse files:' + filesTemp); VAR inputFile = files.inputFile[0]; VAR = uploadedPath inputFile.path; VAR dstPath ='./public/files'+ inputFile.originalFilename rename file name is true; / / fs.rename (uploadedPath, dstPath, function (ERR) {if (ERR) {console.log ('rename error:' + ERR);}else ('rename; OK') {console.log}})} (res.writeHead 200, {'content-type':'text/plain; charset=utf-8'}; res.write ('received) upload:nn'(util.inspect (res.end); {fields: fields, files: fi })})})))) module.exports = router; 

hopes that this article will help you in the design of nodejs programs.

you might be interested in this article:

This concludes the body part

This paper fixed link: | Script Home | +Copy Link

Article reprint please specify:Nodejs method of uploading file based on Express | Script Home

You may also be interested in these articles!