How to Implement frontend back-end communication and upload of images through Express-the storage database (mysql) Tutorial (I) _ javascript skills

Source: Internet
Author: User
This article mainly introduces how Express implements frontend and backend communication and uploads the image storage database (mysql). (1) if you need it, you can refer to it for more than a year, finally, I made up my mind to write down my first blog (although the content is less original, it is an integrated content). The reason why I started using express was that I wanted to test and receive pictures uploaded from the front end and return them, upload images. The backend users are very busy again. They can't do it anymore. They can only do it on their own (ah, they are all forced out ).

This tutorial is suitable for front-end web development that has never touched node, and quickly builds its own framework based on express4.x.

First, install express at http://www.expressjs.com.cn/starter/installing.html. The installation process is completed when you go back to the ground.

After the installation is complete, continue to install the express Application skeleton and generate the default Project

$ npm install express-generator -g 

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

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

Then install all the dependent packages:

$ npm install 

Start this application (MacOS or Linux ):

$ DEBUG=myapp npm start 

Run the following command on Windows:

> set DEBUG=myapp & npm start 

When you see this page, you have completed the basic project construction, and you can continue to add your own code. (After that, you can change the folder in the public directory to your favorite format, such as js and css, which is just a path)

Next, you can add your own page to the project. However, I only find that the jade template and ejs can be loaded by express. You don't have to worry about learning jade again. In fact, the jade writing method is really simple. You can get started with the api. Click here for the learning address. (Jade has been integrated in the project, so you do not need to install it again)

Now you can open the core app. js

These lines define express routes. You can briefly understand the role of routes.

For example, if you open the http: // localhost: 3000/users page, you can understand the code in user. js at a glance. (A get request occurs when this page is opened)

Next, we will test the post and get requests sent by the front end without having to upload images urgently.

Take the post request as an example. Let's change layout. jade to the following format:

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

Create an index under public/js. js, loading jquery (just for short ajax) Someone may ask why there is no public path, because Express's built-in express. static allows you to easily host static files, such as sample files, CSS files, and JavaScript files. For details, click here, corresponding to the app. js content is app. use (express. static (path. join (_ dirname, 'public ')));

Only in this way can the file be read.

Next, modify the js Code, public/js/index. write the most basic ajax request in js. The request path here is "/", which means to send a request to the home page (the routing must be understood, and the routing must be understood, routing must be understood !!)

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

Then modify it 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; 

THE post request, req. body. num indicates the data sent. You can print the req directly to see what is included in it and learn more (remember to restart express after modifying the file ).

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

Now, you can use node to receive requests sent from the front end (is it fun !!), Next, we will upload images.

Because it is a test interface, the company's projects should be compatible with low-version browsers, and all plupload. js will be available (not the method I don't want to use h5 ). Official website. After the download, it will be enough. (Remember to load it in layout. jade)

Modify index. js to the following. This is a standard official website upload example. If you do not understand it, you can check the api on the official website and understand it very well (in fact, you can also understand the variable name ~)

$(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 += '

' + file.name + ' (' + plupload.formatSize(file.size) + ')

'; }); }, UploadProgress: function(up, file) { document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '' + file.percent + "%"; }, 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 changed to the following format. It is mainly used to add the upload and click elements and add two buttons. (do not abandon it. It is really ugly --)

extends layoutblock content h1= title p Welcome to #{title} #filelist #container a#pickfiles select files a#uploadfiles upload files 

Here we will use the node-formidable module developed by Felix Geisend örfer. It abstracts the parsed file data. In fact, to put it bluntly, processing file uploads is "processing POST data"-but the trouble is that it is more appropriate to deal with specific details.

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 form directory. 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:
"); Res. write (" "); res. end ();})}});});

Module. exports = router;

In this case, you need to manually create the folder upload and the temp folder below under public.

Upload the file to a temporary folder, and then rename it through fs to the specified directory.

Fs. rename is renamed, but fs. rename cannot boast that the disk moves files. Therefore, we need to specify that the temporary directory to be uploaded must be in 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 of the uploaded file. The front-end only needs to append the tag to the page.

Complete the frontend image upload function !!

Here we are going to explain how to connect a node to a database tomorrow.

Related Article

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.