Express implementation of front-end communication upload pictures, storage database (MySQL) fool tutorial (iii) End of article

Source: Internet
Author: User

Finally completed all of their own desired function (to encourage themselves), although still very humble, but still quite satisfied with the feeling, haha.

To get to the point, in the second chapter has completed the connection database, and the implementation of the database additions and deletions, let us implement the uploaded image storage database, and on the second visit to return this uploaded image.

The problem that was encountered yesterday is this, because the page will read the template (routes/index.js), the code is as follows:

function (req, res) {    res.render (' index ', {        ' Meng soul ',    });});

So the data can no longer be retrieved under this route (because the path of the picture is requested from the database when the second page is accessed), we can only send a request to get the data, so we use middleware, the usage of the routing middleware http://www.expressjs.com.cn/guide/ Using-middleware.html#middleware.router.

The middleware usage here is as follows (and the problem is that the official web does not have a clear idea of how to send the requested format on the front end)

function (req, res) {           if (req.params.id = = = "Me") {        //dosomething     }})

The front-end send request is this:

function (data) {        //dosomething      });

(Not very simple, but there is no documentation, Cry cry), express get parameters There are three ways:

/user/? id=12Checks urlencoded body params (req.body), ex:id=

1, for example:127.0.0.1:3000/index, in this case, we have to get index, we can get by using Req.params.index (our example is this method), In this way, we can deal with the routing problem in node very well, and it is very convenient to implement the MVC pattern.

2, for example:127.0.0.1:3000/index?id=12, in this case, this way is to get the client get method passed over the value, by using req.query.id can be obtained, A Get method similar to PHP;

3, for example:127.0.0.1:3000/index, and then post a id=2 value, this way is to get the client post data, can be obtained through req.body.id , A post method similar to PHP;

Next to the GET request to add a callback, mainly to access the database, the query has no picture of the path, and then added to the page, the code is as follows:

  

Router.get ('/:id ',function(req, res) {//Create a connection    if(Req.params.id = = = "Me") {        varConnection =mysql.createconnection ({host:' 127.0.0.1 ', User:' Root ', Password:' 111 ', Port:' 3306 ', Database:' Nodesample ',        }); Connection.connect (function(err) {if(Err) {Console.log (' [query]-: ' +err); return; } console.log (' [Connection connect] succeed! ');        }); //Execute SQL statement        varUsergetsql = ' SELECT * from UserInfo '; //CheckConnection.query (Usergetsql,function(err, result) {if(Err) {Console.log (' [SELECT ERROR]-', Err.message); return; }            if(Result[0]!==undefined) {Res.send (result[0])} console.log ('--------------------------SELECT----------------------------'); Console.log (Result); Console.log ('-----------------------------------------------------------------\ n ');        }); //Close ConnectionConnection.end (function(err) {if(err) {return; } console.log (' [Connection end] succeed! ');    }); }})

Here we query the already established UserInfo table, the return result is all the data in the database, the command line can see the print, here only return the first data, in the actual application should also pass a user's ID, to match the data in the database. This ID will also be matched on upload and will be updated if the same occurs.

These need everyone to do their own work, and now ensure that the UserInfo table is empty, the next time the upload is guaranteed to read this data.

The image upload code is modified as follows:

Router.post ('/',function(req, res) {//Console.log (res);    //res.send (req.body);    varform =NewFormidable.    Incomingform (); Form.uploaddir= "./public/upload/temp/";//Change Temp directoryForm.parse (req,function(Error, fields, files) { for(varKeyinchfiles) {            varFile =Files[key]; varFName = (NewDate ()). 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); varUploaddir = "./public/upload/" +FName; Fs.rename (File.path, Uploaddir,function(err) {if(Err) {Res.write (Err+ "\ n");                Res.end (); }                varConnection =mysql.createconnection ({host:' 127.0.0.1 ', User:' Root ', Password:' 111 ', Port:' 3306 ', Database:' Nodesample ',                });                Connection.connect (); varUseraddsql = ' INSERT into UserInfo (id,username,userpass) VALUES (0,?,?) '; varUseraddsql_params = [' path ', '/upload/' +FName]; //IncreaseConnection.query (Useraddsql, Useraddsql_params,function(err, result) {if(Err) {Console.log (' [INSERT ERROR]-', Err.message); return; } console.log ('--------------------------INSERT----------------------------'); //console.log (' INSERT ID: ', Result.insertid); Console.log (' INSERT ID: '), result); Console.log ('-----------------------------------------------------------------\ n ');                });                Connection.end (); Res.write (");            Res.end (); })        }    });});

After uploading the image, the path of the image is stored in the database and can be returned on the second visit.

The front-end request can be written like this:

function (data) {        ifnull | | data!== undefined) {            $ ("Body"). Append ($ ("        })                       ;

Append the image directly in the page, Src gets it from the returned data.

OK, now you can restart Express, upload a picture, in the Refresh page, you can see the image just uploaded!!

Good tutorial to this successful conclusion, their first blog, the process of the harvest a lot, also please find the problem, more comments, greatly appreciated, finally attached the entire project source code, click to download,

After decompression run express startup code is good, run unsuccessful first configure the database!!

Set Debug=myapp & NPM start

Mac

Debug=myapp NPM Start

Good luck to all of you ~

Express implementation of front-end communication upload pictures, storage database (MySQL) fool tutorial (iii) End of article

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.