NODE07---POST request, form submission, file upload

Source: Internet
Author: User

<! DOCTYPE html>Name:<input type= "text" name= "name" > </p> <p>Gender:<input type= "Radio" name= "Sex" value= "male" >male<input type= "Radio" name= "Sex" value= "women" >female</p> <p>Hobbies:<input type= "checkbox" name= "hobby" value= "Sleep"/> Sleep <input type= "checkbox" name= "hobby" value= "eat"/&G t; eat <input type= "checkbox" name= "hobby" value= "soccer"/> Soccer </p> <p>Photo:<input type= "File" name= "Tupian"/> </p> <p> <input type= "Submit"/> </p> </form></body>
/** * Poest submit a form*/varHTTP = require ("http");varQueryString = Require ("querystring");//Creating a servervarServer = Http.createserver (function(Req,res) {//each time the request executes the function, the outside is already executed.         //If your access address is this, and the request type is post    if(Req.url = = "/dopost" && req.method.toLowerCase () = = "POST") {Console.log ("Req.url:" +Req.url); Console.log ("Req.method:" +Req.method); varAllData = ""; //here is a POST request to receive a formula, node in order to pursue the ultimate, it is a small segment of a small segment received.         //accept a short paragraph, perhaps to others to serve. Prevents an oversized form from blocking the entire process, asynchronous operation. Req.addlistener ("Data",function(chunk) {alldata+=Chunk;        }); //all transmissions complete .Req.addlistener ("End",function(){            varDatastring =alldata.tostring (); Res.end ("Success"); //Convert datastring to a JSON object            varDataobj =Querystring.parse (datastring);            Console.log (Dataobj);            Console.log (Dataobj.name);        Console.log (Dataobj.sex);    }); }}); Server.listen (3000, "127.0.0.1");

third, POST request1varAllData = "";2//here is a formula that the POST request receives3//node in order to pursue the Acme, it is a small segment of a small segment received. 4//accept a short paragraph, perhaps to others to serve. Prevents an oversized form from blocking the entire process5 Req.addlistener ("Data",function(chunk) {6 AllData + =Chunk;7        });8//all transmissions complete .9 Req.addlistener ("End",function(){10Console.log (alldata.tostring ());Res.end ("Success");12}), native write post processing, more complex, to write two listening. File upload business is difficult to write. So, use a third-party module. Formidable. As long as the file upload is involved, the form tag is added with a property:1<form action= "Http://127.0.0.1/dopost" method= "post" enctype= "Multipart/form-data" >
/** * File Upload, change the form submission method. */varHTTP = require ("http");varFormidable = require (' formidable '));varUtil = require ("Util"); Console.log ("QQQ");//Creating a servervarServer = Http.createserver (function(req,res) {//If your access address is this, and the request type is postConsole.log ("QQQQQQQ"); if(Req.url = = "/dopost" && req.method.toLowerCase () = = "POST"){        varform =NewFormidable.        Incomingform (); //set File Upload storage addressForm.uploaddir = "./uploads"; //when the callback function is executed, the form is fully received.         //The name sex is all in the Fields object, files is the fileForm.parse (req,function(Err, fields, files) {if(err) {Throwerr;            } console.log (fields);            Console.log (files);            Console.log (Util.inspect ({fields:fields, files:files})); //all text fields, radio boxes, are stored in field;            //all file domains, filesRes.writehead, {' Content-type ': ' Text/plain '}); Res.end (Success);    }); }}); Server.listen (3000);

File Upload and rename

/** * Created by Danny on 2015/9/20 15:35.*/varHTTP = require ("http");varFormidable = require (' formidable '));varUtil = require ("Util");varFS = require ("FS");varSD = require ("Silly-datetime");varPath = require ("path");//Creating a servervarServer = Http.createserver (function(req,res) {//If your access address is this, and the request type is post    if(Req.url = = "/dopost" && req.method.toLowerCase () = = "POST"){        //creates a new incoming form.        varform =NewFormidable.        Incomingform (); //set File Upload storage addressForm.uploaddir = "./uploads"; //when the callback function is executed, the form is fully received. Form.parse (req,function(Err, fields, files) {//if (err) {            //throw err;            //}            //Console.log (Util.inspect ({fields:fields, files:files}));            //time, using a third-party module, Silly-datetime            varTTT = Sd.format (NewDate (), ' Yyyymmddhhmmss '); varran = parseint (Math.random () * 89999 + 10000); varExtname =Path.extname (files.tupian.name); //Perform renaming            varOldPath = __dirname + "/" +Files.tupian.path; //The new path consists of three parts: timestamp, random number, extended name            varNewPath = __dirname + "/uploads/" + TTT + ran +Extname; //renamingFs.rename (Oldpath,newpath,function(err) {if(err) {ThrowError ("Rename failed"); } res.writehead ($, {' Content-type ': ' Text/plain '}); Res.end (Success);        });    }); }Else if(Req.url = = "/"){        //presenting form.html pageFs.readfile ("./form.html",function(err,data) {Res.writehead ($, {' Content-type ': ' text/html '});        Res.end (data); })    }Else{Res.writehead (404, {' Content-type ': ' text/html '}); Res.end ("404"); }}); Server.listen (80, "192.168.41.36");

NODE07---POST request, form submission, file upload

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.