node.js--image upload and display

Source: Internet
Author: User

Introduced

Do a demo, page upload pictures and image names, and then display the uploaded images and their names (using the jade template)

Problem

How is the 1.jade template installed?

2.jade template How to use, grammar rules?

3. Code logic?

How is the 1.jade template installed?

The installation of the Jade template is simple, just execute the command under the specified path NPM install Jade

After installation is such (), the file path under the Node_modules also appears Jade

2.jade template Syntax

Jade is a template engine that uses certain grammatical rules to write HTML pages and to pass variables into them. There are some rules when writing HTML pages:

(1) The relationship between the label and the sub-label. is controlled by a space, and on its right is full of its sub-tags, which indicates that the label is closed when it encounters a label with its same column down.

(2) The writing of the label. In Jade, the HTML represents the

(3) ID and class. In jade, the ordinary HTML statement <div id= "contain" class= "main Other-class" ></div> was rewritten as

Div#contain.main.other-class

(4) property. In jade, the attribute value is written in parentheses, like <link rel= "stylesheet" href= "Static/style.css" > is rewritten as

Link (rel= "stylesheet", href= "Statc/style.css")

3. Code Logic

(1) Edit page Index.jade and Show.jade,index.jade are form Forms page, Show.jade is to show the picture page

Index.jade

HTML    head        meta (charset= "Utf-8")        title choose a picture    body        form (enctype= "Multipart/form-data ", action=" upload ", method=" POST ")            input (type=" file "Name=" theimage ")            input (type=" Submit "value=" Upload image ")

Show.jade

HTML    head        meta (charset= "Utf-8")        title show Image    Body        div            p.title Picture Show            img.image (src= "#{imageurl}")

(2) Logic processing server.js

The module used by the 1.require.

2. Write the server, Res object add render function, used to parse jade, output page.

3. Routing implementation. '/' Show index page, '/upload ' process upload file and show Show page.

4. Writing logic that shows the index page and the upload function

varHTTP = require (' http '), URL= require (' URL '), FS= Require (' FS '), QueryString= Require (' querystring '), Static_module= require ('./node_modules/static_module/static_module ')), Jade= Require (' Jade '), Formidable= Require (' formidable '); Http.createserver (function(req, res) {Res.render=function(jadetemplate, options) {varstr = Fs.readfilesync (jadetemplate, ' UTF8 ')); varfn = Jade.compile (str, {filename:jadetemplate, pretty:true}); varpage =fn (options); Res.writehead ({' Content/type ': ' text/html '});//Output Pageres.end (page);    }; varpathname =decodeURI (Url.parse (req.url). Pathname); if(Pathname = = ' Favicon.ico '){        return; }    Switch(pathname) { Case‘/‘: Showindex (req, res);  Break;  Case'/upload ': Upload (req, res);  Break; default: Static_module.getstaticfile (Pathname, res, req); }    functionShowindex (req, res) {Res.render (' Index.jade ', {});    }; functionUpload (req, res) {varform =NewFormidable.        Incomingform (); Form.parse (req,function(Error, fields, files) {varFileName = Date.parse (NewDate ()) + '-' +Files.theImage.name; Fs.renamesync (Files.theImage.path, __dirname+ '/uploadfile/' +fileName); Res.render (' Show.jade ', {' ImageURL ': '/uploadfile/' +fileName});    }); };}). Listen (1337);

Static_module Module Logic:

/** * * define global common variables*/varBase_dir =__dirname, CONF= Base_dir + '/conf/', STATIC= __dirname + '/. /..‘, Cache_time= 60*60*24*365, mmieconf;/** * * * require node. JS module required for this module*/varSYS = require (' Util '), HTTP= Require (' http '), FS= Require (' FS '), URL= require (' URL '), Path= Require (' path '); Mmieconf=getmmieconf ();/** * * response to static resource requests * @param string Pathname * @param object res * @return NULL*/Exports.getstaticfile=function(Pathname, res, req) {varExtname =path.extname (pathname); Extname= Extname? Extname.slice (1): "; varRealpath = STATIC +Pathname;console.info (Realpath); varMmietype = Mmieconf[extname]? Mmieconf[extname]: ' Text/plain '; Fs.exists (Realpath,function(exists) {if(!exists) {Res.writehead (404, {' Content-type ': ' Text/plain '}); Res.write ("This request URL" + pathname + "is not found on this server.");        Res.end (); } Else {            varFileInfo =Fs.statsync (Realpath); varLastModified =fileInfo.mtime.toUTCString (); /*setting up the cache*/            if(Mmieconf[extname]) {varDate =NewDate (); Date.settime (Date.gettime ()+ cache_time * 1000); Res.setheader ("Expires", date.toutcstring ()); Res.setheader ("Cache-control", "max-age=" +cache_time); }            if(req.headers[' if-modified-since ') && lastmodified = = req.headers[' if-modified-since ']) {Res.writehead (304, "Not Modified");            Res.end (); } Else{fs.readfile (Realpath,"Binary",function(err, file) {if(Err) {Res.writehead (, {' Content-type ': ' Text/plain '});                        Res.end (ERR); } Else{Res.setheader ("Last-modified", lastmodified); Res.writehead (The "Content-type": Mmietype}); Res.write (file,"Binary");                    Res.end ();          }             }); }        }      });}//Get Mmie configuration information, read the configuration filefunctiongetmmieconf () {varRoutermsg = {}; Try{        varstr = fs.readfilesync (CONF + ' mmie_type.json ', ' UTF8 '); Routermsg=json.parse (str); }Catch(e) {Sys.Debug ("JSON Parse Fails")    }    returnroutermsg;}

Other than that:

(1) The static file management module is used./static_module.js, read to the static file according to the path.

(2) The image is obtained using the formidable module.

var formidable = require (' formidable '); var New // do not know what this is to do, is new a formidable. Incomingform () object function(Error, fields, files) {// Async callback     Console.info ( Files.image, files.image.path,files.image.name);     // Image file , picture file path, image file name });

(3) Upload file, form form should set property enctype= "Multipart/form-data"

node.js--image upload and display

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.