Express realize front-end back-end communication upload image storage database (MySQL) Fool-type tutorial (i) _javascript skills

Source: Internet
Author: User

In the front of the pit for more than a year, and finally determined to write their first blog (although the content of the original home less, is an integrated content), began to use express because they want to test receive the front end upload pictures and return to achieve picture upload. After the end of the big people are more busy, no way, can only own on the (hey, are forced out).

This tutorial is suitable for Web front-end development without contact with node, quickly building its own framework, based on express4.x.

First install Express, http://www.expressjs.com.cn/starter/installing.html, the installation process has been a return to the end of OK.

After the installation is complete, continue to install the Express application skeleton and build the default project

 
 

(-G indicates a global installation, which can be used directly next time without installing again)

Then the Express is run directly under the MyApp folder, and the project directory is directly generated

Then install all dependent packages:

 
 

Start this application (MacOS or Linux platform):

 
 

The Windows platform uses the following command:

 
 

See this page, you have completed the foundation of the project build, continue to add their own code on it. (After this, you can change the folder in the public directory for your favorite format, such as: Js,css, just a path)

Then everyone can add their own pages to the project, but express to the present I only found that can load jade templates and Ejs. We do not have to worry about the new learning jade, here http://www.html2jade.org/, you can directly use the tools to convert HTML into Jade template, you can get your hands on the project directly added to the jade template in Express loading method: http ://www.expressjs.com.cn/guide/using-template-engines.html. In fact, Jade's writing is really very simple, we look at the basic API can be started, learning address point here. (The project has integrated jade, do not have to repeat the installation)

Now, everybody, open up the core app.js.

These lines define express routing, we can understand the role of routing, http://www.expressjs.com.cn/guide/routing.html, this is very important, must understand, not difficult, should be able to quickly understand.

For example, now you open the Http://localhost:3000/users page, corresponding to the user.js inside the code a look can be understood. (A GET request occurs when this page is opened)

Let's not rush to upload the pictures, first Test the post and get requests sent by the front end.

Take the POST request as an example, let's change the Layout.jade to 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
 

Create a new index.js under Public/js, load jquery (just for abbreviated AJAX) Someone may ask why there is no public path, because the express built-in express.static can easily host static files, such as pictures, CSS, JavaScript files, etc., detailed content points here, corresponding app.js content for the App.use (Express.static (Path.join (__dirname, ' public '));

This is the only way to read to a file.

The following start to modify the JS code, public/js/index.js write a basic Ajax request is good, here to send the requested path is "/", is to the home page to send requests (Route must understand, route must understand, Route must understand!!) )

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

And then modify it inside the 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);
});

In this monitoring of the first page of the POST request, Req.body.num said sent over the data, you can directly print the next req, see what content contained inside, deepen understanding (after modifying the file remember to restart Express).

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

Now you can use node to receive the request from the front end (is not the gray long happy!!) ), below for our play, upload the picture.

Because it is the test interface, the company's project to be compatible with the lower version of the browser, all plupload.js on the field (not I do not want to use the H5 method). Official website, download after the picture, it is enough. (Remember to load in Layout.jade)

Change the index.js to the following appearance, this is a standard official online biography, do not understand in the official website look at the API, very good understanding (in fact, see variable name can also understand ~)

$ (document). Ready (function () {var uploader = new Plupload. Uploader ({runtimes: ' Html5,flash,silverlight,html4 ', Browse_button: ' Pickfiles ',//can pass ID ... container:d Ocument.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 '). Innerht ML = = ' <div id= ' + 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 then file has finished uploading $ ("body"). Append ($ (info.response
 )}, Uploadcomplete:function (up, file) {}}});
Uploader.init ();  })

Index.jade modified to look like this, mainly add the upload click Element, added two buttons just (do not abandon it is really ugly-)

Extends layout block
content
 h1= title
 p Welcome to #{title}
 #filelist
 #container
 a# Pickfiles Select files
 

The external module we are going to use here is the Node-formidable module developed by Felix Geisendörfer. It does a good job of abstracting the data from the uploaded file. In fact, processing file upload "is" processing post data-but, the trouble is in the specific processing details, so, here, the use of ready-made plans more appropriate point.

Install the formidable module.

 
 

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 Soul '}); Router.post ('/', function (req, res) {var form = new Formidable.
 Incomingform (); Form.uploaddir = "./public/upload/temp/";
 Change Temp 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 (" 

Module.exports = router;

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

Upload files to the temporary folder, and then through the FS rename moved to the specified directory.

Fs.rename is renamed, but Fs.rename cannot move files on the disk, so we need to specify that the uploaded temporary directory is under the same disk as the final directory.

Res.write is back to the front end of the data, here I return an IMG tag directly, and add the path to upload files, the front-end as long as the label append to the page on the OK.

Complete the front-end image upload function!!

Today we are going to do a presentation on the node connection database operation tomorrow.

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.