Home>

It's been over a year in the front pit,I finally made up my mind to write my first blog (although the content is very original,Be considered as integrated content), the reason I started to use express is because I want to test and receive the uploaded image from the front end and returnAchieve image upload.Everyone in the back end is busy again,no solution anymore,I can only go on my own (hey, it was forced out).

Tutorial This tutorial is suitable for web front-end development without any contact with node.Quickly build your own framework,Based on express4.x.

First install express. During the installation process, keep pressing Enter until it is ok.

After installation,Continue to install the application skeleton of express,Build default project

$npm install express-generator -g

(-G means global installation,Can be used directly next time,No need to install again)

Then run express directly under the myapp folder, and the project directory is directly generated

Then install all dependencies:

$npm install

Launch this application (macos or linux platform):

$debug=myapp npm start

Windows platform uses the following commands:

>set debug=myapp&npm start

When you see this page,You have completed the basic project construction,Continue adding your own code to it.(After this, you can modify the folders in the public directory to your favorite format,For example:js, css, just a path)

Next you can add your own pages to the project,However, so far I only found that jade templates and ejs can be loaded. You do n’t need to worry about learning jade again. Here, you can directly use tools to convert html to jade templates. You can directly add existing projects in your hands.Jade template loading method in Express :. In fact, the way jade is written is really simple,If you look at the api, you can get started.Click here for the study address.(Jade has been integrated in the project, no need to repeat the installation)

Now everyone open the core app.js

These lines define the routing of express. You can simply understand the role of routing.,This point is very important,Must understand,Not difficultIt should be understood quickly.

For example, now that you open the page, the code in user.js can be understood at a glance.(A get request occurred when opening this page)

Let ’s not rush to upload pictures below,First test the post and get requests sent by the front end.

Take post request as an example,Let's modify layout.jade to look like the following

doctype html
html
 head
 title=title
 link (rel="stylesheet", href="/css/style.css")
 script (type="text/javascript", src="/js/jquery.js")
 script (type="text/javascript", src="/js/index.js")
 body
 block content

New Create a new index.js under public/js, load jquery (just for short ajax), someone may ask why there is no public path, because express's built-in express.static can easily host static files,Such as pictures, css, javascript files, etc. For details, click here,The corresponding app.js content is app.use (express.static (path.join (__ dirname, "public")));

Only then can the file be read.

Begin to modify the js code, just write the most basic ajax request in public/js/index.js,The path to send the request here is "/", which is to send the request to the homepage (the routing must be understood,The routing must be understood,The routing must be understood! !! )

$(document) .ready (function ()
{
$.post ("/", {num:"12345678"
}, function (data)
{
 console.log (data)
 });
})

Then modify in routes/index.js

var express=require ("express");
var router=express.router ();
/* get home page. * /
router.get ("/", function (req, res, next) {
 res.render ("index", {title:"express"});
});
router.post ("/", function (req, res) {
 res.send (req.body.num);
});
module.exports=router;

monitor Here is the post request on the homepage, req.body.num represents the data sent,You can print req directly to see what it contains,Deepen your understanding (remember to restart express after modifying the file).

At this time, you can see the returned data in the console.

Now everyone can use node to receive the request sent by the front end (isn't it gray long happy !!!), let ’s do our highlightupload image.

Because it is a test interface,The company's project needs to be compatible with earlier versions of the browser,All plupload.js comes into play (not the way I don't want to use h5). Official website, as shown below,That's enough.(Remember to load in layout.jade)

modify Modify index.js to look like the following,This is a standard official website example.If you do n’t understand, look at the api on the official website and understand it well.

$(document) .ready (function () {
 var uploader=new plupload.uploader ({
 runtimes:"html5, flash, silverlight, html4", browse_button:"pickfiles", //you can pass an id ...
 container:document.getelementbyid ("container"), //... or dom element itself
 url:"/", flash_swf_url:"../js/moxie.swf", silverlight_xap_url:"../js/moxie.xap", filters:{
 max_file_size:"10mb", mime_types:[{
 title:"image files", extensions:"jpg, gif, png"
 }, {
 title:"zip files", extensions:"zip"
 }]
 }, init:{
 postinit:function () {
 document.getelementbyid ("filelist"). innerhtml="";
 document.getelementbyid ("uploadfiles"). onclick=function () {
 uploader.start ();
 return false;
 };
 }, filesadded:function (up, files) {
 plupload.each (files, function (file) {
 document.getelementbyid ("filelist"). innerhtml +="<div + file.id +" ">" + file.name + "(" + plupload.formatsize (file.size) + ")<b></b></div>";
 });
 }, uploadprogress:function (up, file) {
 document.getelementbyid (file.id) .getelementsbytagname ("b") [0] .innerhtml="&span>" + file.percent + "%</span >"
 }, error:function (up, err) {
 document.getelementbyid ("console"). appendchild (document.createtextnode ("\ nerror #" + err.code + ":" + err.message));
 }, fileuploaded:function (up, file, info) {//called when file has finished uploading
 $("body"). append ($(info.response))
 }, uploadcomplete:function (up, file) {
 }
 }
 });
 uploader.init ();
})

Index.jade is modified as follows,Mainly add elements for upload clicks,Added two buttons (don't disappoint it is really ugly-)

extends layout
block content
 h1=title
 p welcome to #{title}
 #filelist
 #container
 a #pickfiles select files
 a #uploadfiles upload files

The external module we are going to use here is the node-formidable module developed by felix geisend&rfer. It makes a good abstraction for parsing uploaded file data. Actually,Processing file uploads "is" processing post data-but the trouble is in the specific processing details,Therefore, it is more appropriate to use a ready-made solution here.

Install the formidable module.

npm install formidable

Modify routes/index.js

var express=require ("express");
var router=express.router ();
var fs=require ("fs");
var formidable=require ("formidable");
/* get home page. * /
router.get ("/", function (req, res) {
 res.render ("index", {
 title:"Meng Xinghun"
 });
});
router.post ("/", function (req, res) {
 var form=new formidable.incomingform ();
 form.uploaddir="./public/upload/temp/";//Change the temporary directory
 form.parse (req, function (error, fields, files) {
 for (var key in files) {
 var file=files [key];
 var fname=(new date ()). gettime ();
 switch (file.type) {
 case "image/jpeg":
 fname=fname + ".jpg";
 break;
 case "image/png":
 fname=fname + ".png";
 break;
 default:
 fname=fname + ".png";
 break;
 }
 console.log (file, file.size);
 var uploaddir="./public/upload/" + fname;
 fs.rename (file.path, uploaddir, function (err) {
 if (err) {
 res.write (err + "\ n");
 res.end ();
 }
 //res.write("upload image:<br />");
 res.write ("<img src ="/upload/"+ fname +" "/>");
 res.end ();
 })
 }
 });
});

module.exports=router;

At this time, you need to manually create a new folder upload and the temp folder under public.

First upload the file to a temporary folder,Then rename to fs and move to the specified directory.

Fs.rename is renamed,But fs.rename cannot exaggerate disk moving files,So we need to specify that the uploaded temporary directory is on the same disk as the final directory.

Res.write is the data returned to the front end,Here I directly return an img tag and add the path to upload the file,The frontend just needs to append the tag to the page.

Complete the front-end picture upload function! !!

To Go here today,Tomorrow will explain the operation of node connection to the database.

  • Previous Write a PHP script to implement the pagination of comments in WordPress
  • Next JS to achieve the New Year countdown effect