Easily create nodejs server (10): process uploaded image _ node. js

Source: Internet
Author: User
Tags tmp folder
This article describes how to easily create a node. js server (10): process uploaded images. this is the last article in the series. it contains a complete example of how to process uploaded images, for more information, see the following section. you can upload an image and display it in your browser.

Here we will use the node-formidable module developed by Felix Geisend örfer. It abstracts the parsed file data.

To install this external module, run the following command in cmd:

The code is as follows:


Npm install formidable


If similar information is output, the installation is successful:

The code is as follows:


Npm info build Success: formidable@1.0.14


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

The code is as follows:


Var formidable = require ("formidable ");


In this module, the form submitted through the http post request can be parsed in Node. js. What we need to do is create a new IncomingForm, which is an abstract representation of the submitted Form. after that, we can use it to parse the request object and obtain the required data fields in the form.

The image files in this case are stored in the/tmp folder.

First, let's solve a problem: how can we display files stored in the local hard disk in a browser?

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

We will add the/showURL request processing program, which is hardcoded to display the file/tmp/test.png in the browser. Of course, you must first save the image to this position.

Our team requestHandlers. js made some modifications:

The code is as follows:


Var querystring = require ("querystring "),
Fs = require ("fs ");
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body =''+
''+
' 'Content = "text/html; charset = UTF-8"/> '+
''+
''+
''+
''+
'';
Response. writeHead (200, {"Content-Type": "text/html "});
Response. write (body );
Response. end ();
}
Function upload (response, postData ){
Console. log ("Request handler 'upload' was called .");
Response. writeHead (200, {"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 'was called .");
Fs. readFile ("/tmp/test.png", "binary", function (error, file ){
If (error ){
Response. writeHead (500, {"Content-Type": "text/plain "});
Response. write (error + "\ n ");
Response. end ();
} Else {
Response. writeHead (200, {"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 ing table in index. js:

The code is 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 the server is restarted, access http: // localhost: 8888/show to view the image saved in/tmp/test.png.

Okay. what we need at last is:

Add a file Upload element to the/start form.

Worker integrates node-formidable into our upload request processing program to save the uploaded image to/tmp/test.png

Embed the uploaded image into the HTML output by/uploadURL

The first item is very simple. You only need to add a multipart/form-data encoding type in the HTML form, remove the previous encoding area, and add a file Upload component, change the text of the submit button to "Upload file. The following shows requestHandler. js:

The code is as follows:


Var querystring = require ("querystring "),
Fs = require ("fs ");
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body =''+
''+
' 'Content = "text/html; charset = UTF-8"/> '+
''+
''+
''+
''+
'';
Response. writeHead (200, {"Content-Type": "text/html "});
Response. write (body );
Response. end ();
}
Function upload (response, postData ){
Console. log ("Request handler 'upload' was called .");
Response. writeHead (200, {"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 'was called .");
Fs. readFile ("/tmp/test.png", "binary", function (error, file ){
If (error ){
Response. writeHead (500, {"Content-Type": "text/plain "});
Response. write (error + "\ n ");
Response. end ();
} Else {
Response. writeHead (200, {"Content-Type": "image/png "});
Response. write (file, "binary ");
Response. end ();
}
});
}
Exports. start = start;
Exports. upload = upload;
Exports. show = show;

Next, we need to complete the second step, from the server. js start -- remove the processing and request for postData. setEncoding (this part of node-formidable will be processed by itself), instead, it uses the method of passing the request object to the request route:

The code is 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 and pass the request object this time:

The code is 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;

Now, the request object can be used in our upload request processing program. Node-formidable will save the uploaded files to the local/tmp directory.

Make sure that the file is saved as/tmp/test.png.

Next, we put the operations for processing file uploads and renaming together, as shown in requestHandlers. js:

The code is as follows:


Var querystring = require ("querystring "),
Fs = require ("fs "),
Formidable = require ("formidable ");
Function start (response ){
Console. log ("Request handler 'start' was called .");
Var body =''+
''+
' '+
''+
''+
''+
''+
'';
Response. writeHead (200, {"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 (200, {"Content-Type": "text/html "});
Response. write ("received image:
");
Response. write ("");
Response. end ();
});
}
Function show (response ){
Console. log ("Request handler 'show 'was called .");
Fs. readFile ("/tmp/test.png", "binary", function (error, file ){
If (error ){
Response. writeHead (500, {"Content-Type": "text/plain "});
Response. write (error + "\ n ");
Response. end ();
} Else {
Response. writeHead (200, {"Content-Type": "image/png "});
Response. write (file, "binary ");
Response. end ();
}
});
}
Exports. start = start;
Exports. upload = upload;
Exports. show = show;

Here, all our servers are complete.

Some people may encounter the following problems when uploading images:

According to my guess, this problem is caused by disk partitions. to solve this problem, we need to change the default zero-hour folder path of formidable to ensure that it is in the same disk partition as the target directory.

We found the upload function of requestHandlers. js and made some modifications to it:

The code is 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 (200, {"Content-Type": "text/html "});
Response. write ("received image:
");
Response. write ("");
Response. end ();
});
}


We added form. uploadDir = "tmp". now we restart the server and then perform the upload operation. The problem is solved perfectly.

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.