Easy creation of nodejs server (10): Process uploaded images and nodejs upload images

Source: Internet
Author: User
Tags tmp folder

Easy creation of nodejs server (10): Process uploaded images and nodejs upload images

This section describes how to upload an image and display it in a 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:
Copy codeThe Code is as follows:
Npm install formidable

If similar information is output, the installation is successful:
Copy codeThe 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:
Copy codeThe 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:

Copy codeThe Code is as follows:
Var querystring = require ("querystring "),
Fs = require ("fs ");
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body = ''<Head>' +
'<Meta http-equiv = "Content-Type"' +
'Content = "text/html; charset = UTF-8"/> '+
'</Head>' +
'<Body>' +
'<Form action = "/upload" method = "post">' +
'<Textarea name = "text" rows = "20" cols = "60"> </textarea>' +
'<Input type = "submit" value = "Submit text"/>' +
'</Form>' +
'</Body>' +
'</Html> ';
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:

Copy codeThe 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:

Copy codeThe Code is as follows:
Var querystring = require ("querystring "),
Fs = require ("fs ");
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body = ''<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 (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:

Copy codeThe 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:

Copy codeThe 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:

Copy codeThe 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 = ''<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 (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: <br/> ");
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:

Copy codeThe 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: <br/> ");
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.

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.