Easy to create Nodejs server (10): Processing upload pictures _node.js

Source: Internet
Author: User
Tags html form http post readfile tmp folder

In this section, we will implement the user uploading the image and displaying it in the browser.

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.

To install this external module, you need to execute the command under CMD:

Copy Code code as follows:

NPM Install formidable



If you output similar information, it means the installation is successful:


Copy Code code as follows:

NPM Info Build success:formidable@1.0.14



After the installation is successful, we use request to introduce it:


Copy Code code as follows:

var formidable = require ("formidable");



What this module does is that the form that will be submitted via an HTTP POST request can be parsed in node.js. All we have to do is create a new incomingform, which is an abstract representation of the submitted form, which you can then use to parse the request object and get the data fields that are required in the form.

The picture file for this case is stored in the/tmp folder.

Let's solve a problem: how can I display a file saved on a local hard drive in a browser?

We use the FS module to read the files to the server.

Let's add the/showurl request handler, which is directly hard-coded to display the file/tmp/test.png content into the browser. Of course, first you need to save the picture to this location.

Our team Requesthandlers.js to make some changes:

Copy Code code as follows:



var querystring = require ("querystring"),


FS = require ("FS");


function Start (response, PostData) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' +


' <head> ' +


' <meta http-equiv= ' content-type ' +


' Content= ' text/html; Charset=utf-8 "/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' method= ' post ' > ' +


' <textarea name= ' text ' rows= ' cols= ' ></textarea> ' +


' <input type= ' submit ' value= ' submit text '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response, postdata) {


Console.log ("Request handler ' upload ' was called.");


Response.writehead ({"Content-type": "Text/plain"});


Response.Write ("You ' ve sent the text:" + querystring.parse (postdata). Text);


Response.End ();


}


Function Show (response, PostData) {


Console.log ("Request handler ' show ' is called.");


Fs.readfile ("/tmp/test.png", "Binary", function (error, file) {


if (Error) {


Response.writehead (+, {"Content-type": "Text/plain"});


Response.Write (Error + "\ n");


Response.End ();


} else {


Response.writehead ({"Content-type": "Image/png"});


Response.Write (File, "binary");


Response.End ();


}


});


}


Exports.start = start;


Exports.upload = upload;


Exports.show = Show;


We also need to add this new request handler to the Routing mapping table in Index.js:

Copy Code code as follows:

var server = require ("./server");
var router = require ("./router");
var requesthandlers = require ("./requesthandlers");
var handle = {}
handle["/"] = Requesthandlers.start;
handle["/start"] = Requesthandlers.start;
handle["/upload"] = requesthandlers.upload;
handle["/show"] = requesthandlers.show;
Server.start (Router.route, handle);

After restarting the server, you can see the pictures saved in/tmp/test.png by accessing Http://localhost:8888/show.

Well, finally, what we want is:

 Add a file upload element to the/start form

 Integrates node-formidable into our upload request handler to save uploaded images to/tmp/test.png

 The uploaded images into the HTML of the/uploadurl output

The first is very simple. You only need to add a Multipart/form-data encoding type to the HTML form, remove the previous text area, add a file upload component, and change the copy of the submit button to "Upload file". As shown in the following requesthandler.js:

Copy Code code as follows:



var querystring = require ("querystring"),


FS = require ("FS");


function Start (response, PostData) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' +


' <head> ' +


' <meta http-equiv= ' content-type ' +


' Content= ' text/html; Charset=utf-8 "/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' enctype= ' multipart/form-data ' +


' method= ' post ' > ' +


' <input type= ' file ' name= ' upload ' > ' +


' <input type= ' submit ' value= ' Upload file '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response, postdata) {


Console.log ("Request handler ' upload ' was called.");


Response.writehead ({"Content-type": "Text/plain"});


Response.Write ("You ' ve sent the text:" + querystring.parse (postdata). Text);


Response.End ();


}


Function Show (response, PostData) {


Console.log ("Request handler ' show ' is called.");


Fs.readfile ("/tmp/test.png", "Binary", function (error, file) {


if (Error) {


Response.writehead (+, {"Content-type": "Text/plain"});


Response.Write (Error + "\ n");


Response.End ();


} else {


Response.writehead ({"Content-type": "Image/png"});


Response.Write (File, "binary");


Response.End ();


}


});


}


Exports.start = start;


Exports.upload = upload;


Exports.show = Show;


Next, we're going to complete the second step, starting with server.js-removing the PostData and request.setencoding (which the node-formidable itself will handle), Instead, pass the request object to the requesting route:

Copy Code code as follows:

var http = require ("http");
var url = require ("url");
function start (route, handle) {
function onrequest (request, Response) {
var pathname = Url.parse (request.url). Pathname;
Console.log ("Request for" + Pathname + "received.");
Route (handle, pathname, response, request);
}
Http.createserver (ONrequest). Listen (8888);
Console.log ("Server has started.");
}
Exports.start = start;

Next, modify Router.js, this time to pass the request object:

Copy Code code as follows:

function route (handle, pathname, response, request) {
Console.log ("About to route a request for" + pathname);
if (typeof handle[pathname] = = ' function ') {
Handle[pathname] (response, request);
} else {
Console.log ("No request handler found for" + pathname);
Response.writehead (404, {"Content-type": "Text/html"});
Response.Write ("404 Not Found");
Response.End ();
}
}
Exports.route = route;

The request object can now be used in our upload request handler. Node-formidable will process the uploaded files to the local/tmp directory, and we need

The thing to do is to make sure that the file is saved as/tmp/test.png.

Next, we put together the processing of file uploads and renaming, as shown in the following requesthandlers.js:

Copy Code code as follows:



var querystring = require ("querystring"),


FS = require ("FS"),


Formidable = require ("formidable");


function Start (response) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' +


' <head> ' +


"<meta http-equiv=" Content-type "content=" text/html; '+


' Charset=utf-8 '/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' enctype= ' multipart/form-data ' +


' method= ' post ' > ' +


' <input type= ' file ' name= ' upload ' multiple= ' multiple ' > ' +


' <input type= ' submit ' value= ' Upload file '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response, request) {


Console.log ("Request handler ' upload ' was called.");


var form = new Formidable. Incomingform ();


Console.log ("About to parse");


Form.parse (Request, function (Error, fields, files) {


Console.log ("parsing done");


Fs.renamesync (Files.upload.path, "/tmp/test.png");


Response.writehead ({"Content-type": "Text/html"});


Response.Write ("received image:<br/>");


Response.Write ("<img src= '/show '/>");


Response.End ();


});


}


Function Show (response) {


Console.log ("Request handler ' show ' is called.");


Fs.readfile ("/tmp/test.png", "Binary", function (error, file) {


if (Error) {


Response.writehead (+, {"Content-type": "Text/plain"});


Response.Write (Error + "\ n");


Response.End ();


} else {


Response.writehead ({"Content-type": "Image/png"});


Response.Write (File, "binary");


Response.End ();


}


});


}


Exports.start = start;


Exports.upload = upload;


Exports.show = Show;


Do this, our server is complete.

In the process of performing a picture upload, some people may encounter such a problem:

The reason for this problem I guess is due to disk partitioning, and to solve this problem, you need to change the default zero folder path of formidable to ensure that the target directory is on the same disk partition.

We found Requesthandlers.js's upload function and made some changes to it:

Copy Code code as follows:

function upload (response, request) {
Console.log ("Request handler ' upload ' was called.");
var form = new Formidable. Incomingform ();
Console.log ("About to parse");

Form.uploaddir = "TMP";

Form.parse (Request, function (Error, fields, files) {
Console.log ("parsing done");
Fs.renamesync (Files.upload.path, "/tmp/test.png");
Response.writehead ({"Content-type": "Text/html"});
Response.Write ("received image:<br/>");
Response.Write ("Response.End ();
});
}



We added a sentence of Form.uploaddir = "tmp", now reboot the server, and then perform the upload operation, the problem is perfectly resolved.

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.