Nodejs Learning Notes (eight)---node. js + Express upload file function (felixge/node-formidable)

Source: Internet
Author: User

Directory
    • Objective
    • Formidable introduction
    • Create a project and install formidable
    • Implementing the Upload function
    • Run results
    • Part of the Puzzle analysis
    • After the writing
Objective

The previous example of building a Web site, this time on the basis of the general Web features----file Upload, example of an upload image function as an example

The upload function is named with the formidable implementation, the example is simple!

PS: Recently relatively busy, from the last update has been relatively long ^_^!

Formidable introduction

Nodejs native implementation upload or more trouble, have the interest of self to refer to the Internet has written by the user code

Formidable is selected here, but also on GitHub, the same kind of functional module popularity of the relatively high

Https://github.com/felixge/node-formidable

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

  

Advantages: Upload speed is considerable, memory consumption is relatively low, easy to use ...

Create a Project installation formidable

1. Create a project Sampleupload

CD working directory

Express-e Sampleupload

2. Modify the Package.json file to add formidable dependencies

 { "name": "Application-name" ,  " Version ":" 0.0.1 " "private": true  ,  "scripts" " start ":" Node./bin/www " },  "dependencies" " Express ":" ~4.0.0 " "Static-favicon": "~1.0.0" " Morgan ":" ~1.0.0 ",  "Cookie-parser": "~1.0.1" " Body-parser ":" ~1.0.0 "  "Debug": "~0.7.4" " Ejs ":" ~0.8.5 "   

3. Install dependencies

CD sampleupload && NPM Install

Install successfully, everything is ready, start to complete this function!

Implementing the Upload function

  build forms in 1.index.ejs files and implement front-end validation (style usage and http://www.cnblogs.com/zhongweiv/p/nodejs_express_webapp.html consistency)

<! DOCTYPE html>if(locals.success) {%> <div id= "alt_sucess" class= "alert alert-success" > <%-success%&gt           ; </div> <%}%> <%if(locals.error) {%> <div id= "alt_warning" class= "alert alert-warning" > <%= error%> </div> <%}%> <form class= "Form-signin" role= "form" method= "post" Enctype= ' multipart/form-d ATA ' > 

String.prototype.format=function(args) {varresult = This; if(Arguments.length > 0) { if(Arguments.length = = 1 &&typeof(args) = = "Object") { for(varKeyinchargs) { if(Args[key]! =undefined) { varReg =NewRegExp ("({" + key + "})", "G"); Result=Result.replace (Reg, Args[key]); } } } Else { for(vari = 0; i < arguments.length; i++) { if(Arguments[i]! =undefined) { varReg =NewRegExp ("({)" + i + "(})", "G"); Result=Result.replace (Reg, arguments[i]); } } } } returnresult; } $(function(){ $(' #btnSub '). On (' click ',function(){ varFulavatarval = $ (' #fulAvatar '). Val (), Errortip= ' <div id= ' errortip ' class= ' alert alert-warning ' >{0}</div> '; $("#errorTip, #alt_warning"). Remove (); if(Fulavatarval.length = = 0) { $("#container"). Prepend (Errortip.format (' Please select file to upload ')); return false; } varExtname = fulavatarval.substring (Fulavatarval.lastindexof ('. ')), fulavatarval.length). toLowerCase (); if(Extname! = '. png ' && extname! = '. jpg '){ $("#container"). Prepend (Errortip.format (' PNG and JPG only supported images ')); return false; } return true; }) });</script>

Here must pay attention to the enctype property of the form, this is not much to explain, if it is the first contact, see http://www.w3school.com.cn/tags/att_form_enctype.asp

  

  2. Implement upload logic in Index.js

varExpress = require (' Express ') Router=Express. Router (), Formidable= Require (' formidable '), FS= Require (' FS '), TITLE= ' Formidable upload example ', Avatar_upload_folder= '/avatar/'/*GET home page.*/Router.get (‘/‘,function(req, res) {Res.render (' Index ', {title:title});}); Router.post (‘/‘,function(req, res) {varform =NewFormidable. Incomingform ();//Create an upload formform.encoding = ' utf-8 ';//Set EditForm.uploaddir = ' public ' + avatar_upload_folder;//Set upload directoryForm.keepextensions =true;//reserved suffixForm.maxfieldssize = 2 * 1024 * 1024;//File SizeForm.parse (req,function(Err, fields, files) {if(Err) {Res.locals.error=err; Res.render (' Index ', {title:title}); return; }                 varExtname = ";//suffix name        Switch(files.fulAvatar.type) { Case' Image/pjpeg ': Extname= ' jpg ';  Break;  Case' Image/jpeg ': Extname= ' jpg ';  Break;  Case' Image/png ': Extname= ' png ';  Break;  Case' Image/x-png ': Extname= ' png ';  Break; }        if(Extname.length = = 0) {Res.locals.error= ' support only PNG and JPG images '; Res.render (' Index ', {title:title}); return; }        varAvatarname = math.random () + '. ' +Extname; varNewPath = Form.uploaddir +Avatarname;        Console.log (NewPath);  Fs.renamesync (Files.fulAvatar.path, NewPath); // Renaming    }); Res.locals.success= ' Upload successful '; Res.render (' Index ', {title:title}); }); Module.exports= Router;

  

Note: Create the Avatar folder in the public folder for file storage

Run results

1. Add 8000-port monitoring to the App.js

  2.cd to the project root directory, run the node app

3. Access localhost:8000 on the browser

  

4. Uploading Images

  
5. Go to the Upload folder to view

  

Done!

Part of the Puzzle analysis

There are some comments in the code, and I'm not going to explain.

  

1. How can I not see the upload?

Note: Form.parse and look at formidable's explanation.

Automatically writing file uploads to disk

  2. Why do I need fs.renamesync

The reason is related to the previous problem, it will automatically be uploaded to the user's temporary directory (this can be seen Files.fulAvatar.path output) http://nodejs.org/docs/latest/api/fs.html#fs_fs_ Renamesync_oldpath_newpath

3. Can you see the upload progress

Yes, https://github.com/felixge/node-formidable#events (take a closer look at events, there may be other parts you want to use)

But just in the console output, want to display the progress bar at the front end is not possible (not to study, think of other ways should also be able)

  4. FileName want to name UUID does not repeat, what to do in Nodejs?

You can use Node-uuid to invoke simple Https://github.com/broofa/node-uuid

...

Other messages ask, ^_^!

After the writing

function is relatively simple, the code is also an example of style, we mainly focus on the use of

Code Structure Optimization Direction:

1. For example, the file suffix method can be put into a pub.js, this JS dedicated to these public methods

2. The return value can be beneficial to return the data, the front end based on the return value to make the corresponding prompt

3. Can facilitate jquer.form.js to submit the form, post in the Res.json method return value, optimize the experience (also reference this JS will also increase the page volume)

....

In short is a small example, we will look at it ^_^!

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.