node+express Implement file Upload function

Source: Internet
Author: User

In the Development of node Web, we may often encounter the problem of uploading files, this piece if we have no experience, may encounter a lot of pits, below I will share with you some ways to achieve file upload.

First, the node+express file upload common way

Through a period of access to information, groping, I found that the way to implement the upload is: 1.express middleware Multer Module (the most efficient, in express3.x native support, to the express4.x independent into a module), 2.connect-multiparty module (but now officially not recommended), 3. Use Multipa Rty Module implementation (This method is more common), 4. Using the formidable plug-in implementation (plug-ins, is simple to understand);

Second, understand Multipart/form-data

first know enctype This property manages the MIME encoding of the form. A total of three values are optional:

2, multipart/form-data
3, text/plain
where application/x-www-form-urlencoded is the default value, the function is to set the encoding of the form transfer. For example, we have seen Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded") in Ajax; But in HTML form table dropdowns can not write enctype=application/x-www-form-urlencoded, because the default HTML form is this type of transmission encoding. The

Text/plain is the meaning of plain text transmission, when sending the message to set this type of encoding, otherwise there will be the problem of encoding confusion when receiving. Network often take text/plain and text/html to do comparison, in fact, these two very good distinction, the former is used to transfer plain text files, the latter is the transmission of HTML code encoding type, in the sending of the header file is used. ① and ③ cannot be used to upload files, only multipart/form-data can pass the file data intact.

  When we use enctype= ' multipart/form-data ' to submit data with the request payload.

Third, Multer module upload problem

GitHub Address: Https://github.com/expressjs/multer Https://www.npmjs.com/package/multer

Multer is a middleware for node, submitted by the Multipart/form-data type, and can be more efficient if you write the Busboy module at the top (which can quickly parse data from HTML).

Install Multer:

NPM Install--save Multer

Official Basic Examples:

varExpress = require ('Express')varMulter = require ('Multer')varUpload = Multer ({dest:'uploads/' })varApp =Express () App.post ('/profile', Upload.single ('Avatar'), function (req, res, next) {//Req.file is the ' avatar ' file//Req.body'll hold the text fields, if there were any}) App.post ('/photos/upload', Upload.array ('Photos', A), function (req, res, next) {//Req.files is array of ' photos ' files//Req.body would contain the text fields, if there were any})varCpupload = Upload.fields ([{name:'Avatar', MaxCount:1}, {name:'Gallery', MaxCount:8}]) App.post ('/cool-profile', Cpupload, function (req, res, next) {//Req.files is a object (String, array) where FieldName is the key, and the value is array of files//  //e.g. //req.files[' Avatar '][0], File//req.files[' gallery '), Array//  //Req.body would contain the text fields, if there were any})

You can also do this by:

varUpload = Multer ({dest:"uploads/"}). single ('Avatar'); App.post ('/profile', Function (req, res) {upload (req, res, function (err) {if(Err) {console.log (req.body); //Print Request BodyConsole.log (Req.file); //An error occurred when uploading      return    }    //everything went fine  })})

However, finally we have achieved successful upload, with the example of GitHub practiced many times, have not achieved success, I hope that the great God help me to point out.

Four, multiparty module upload problem

GitHub Address: Https://github.com/andrewrk/node-multiparty

With the multiparty module, it is also necessary to use the "Multipart/form-data" type, with the Busboy module to speed up the parsing efficiency.

Install Multiparty:

NPM Install Multiparty

In fact, this is relatively simple:

varMultiparty = require ('Multiparty');varHTTP = require ('http');varUtil = require ('util');varFS = require ("FS"); Http.createserver (function (req, res) {if(Req.url = = ='/upload'&& Req.method = = ='POST') {    //parsing a file upload    varform =Newmultiparty.   Form (); //Set EditForm.encoding ='Utf-8'; //Set file storage pathForm.uploaddir ="uploads/images/"; //set the single file size limitForm.maxfilessize =2*1024x768*1024x768; //form.maxfields = 1000; Set so the sum of the size of the fileform.parse (req, Function (Err, fields, files) {console.log (files.originalfilename);    Console.log (Files.path); //To rename a file name synchronouslyFs.renamesync (files.path,files.originalfilename); Res.writehead ( $, {'Content-type':'Text/plain'}); Res.write ('received upload:\n\n');  Res.end (Util.inspect ({fields:fields, files:files}));    }); return; }  //show a file upload formRes.writehead ( $, {'Content-type':'text/html'}); Res.end ('<form action= "/upload" enctype= "Multipart/form-data" method= "POST" >'+'<input type= "text" name= "title" ><br>'+'<input type= "file" name= "upload" multiple= "multiple" ><br>'+'<input type= "Submit" value= "Upload" >'+'</form>'  );}). Listen (8080);
Five, formidable module upload problem

Formidable upload plugin, is also on GitHub on the same kind of features popular.

GitHub Address: https://github.com/felixge/node-formidable https://www.npmjs.org/package/formidable

Advantages:

1. Fast speed (~500m/s), no non-buffering multipart parsing

2. Automatically write to the upload file disk

3. Low memory consumption

4. Elegant error handling

5. Very high test coverage

Formidable installation:

NPM install [email protected]

Official examples:

varFormidable = require ('Formidable'), HTTP= Require ('http'), Util= Require ('util'); Http.createserver (function (req, res) {if(Req.url = ='/upload'&& req.method.toLowerCase () = ='Post') {    //Create a form upload    varform =NewFormidable.    Incomingform (); //Set EditForm.encoding ='Utf-8'; //Set file storage pathForm.uploaddir ="uploads/images/"; //reserved suffixForm.keepextensions =true; //set the single file size limitForm.maxfieldssize =2*1024x768*1024x768; //form.maxfields = 1000; Set so the sum of the size of the fileform.parse (req, Function (Err, fields, files) {Res.writehead ( $, {'Content-type':'Text/plain'}); Res.write ('received upload:\n\n');    Res.end (Util.inspect ({fields:fields, files:files}));    }); return; }  //show a file upload formRes.writehead ( $, {'Content-type':'text/html'}); Res.end ('<form action= "/upload" enctype= "Multipart/form-data" method= "POST" >'+'<input type= "text" name= "title" ><br>'+'<input type= "file" name= "upload" multiple= "multiple" ><br>'+'<input type= "Submit" value= "Upload" >'+'</form>'  );}). Listen (8080);

Resources:

Express Middleware Multer module: https://github.com/expressjs/multer

If you can't solve the suggestion with Multer Multiparty:https://github.com/andrewrk/node-multiparty

Formidable:https://github.com/felixge/node-formidable

Https://www.npmjs.org/package/formidable

node. JS Learning Series Total Index: http://www.cnblogs.com/zhongweiv/p/nodejs.html

Node-upload-practice:https://cnodejs.org/topic/5470a385a3e2aee40698de20

Node-uuid resolving file name duplication problem: Https://github.com/broofa/node-uuid

node+express Implement file Upload function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.