Home >
Article > Web Front-end > Easily create a nodejs server (10): handle uploaded images_node.js
Easily create a nodejs server (10): handle uploaded images_node.js
WBOYOriginal
2016-05-16 16:25:401405browse
In this section we will implement that the user uploads a picture and displays the picture in the browser.
The external module we are going to use here is the node-formidable module developed by Felix Geisendörfer. It makes a good abstraction for parsing uploaded file data.
To install this external module, you need to execute the command under cmd:
What this module does here is convert the form submitted through HTTP POST request, which 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. After that, we can use it to parse the request object and obtain the required data fields in the form.
The image files of this article’s case are stored in the /tmp folder.
Let’s solve a problem first: How to display files saved on the local hard drive in the browser?
We use the fs module to read files into the server.
Let’s add a request handler for /showURL, which is directly hard-coded to display the contents of the file /tmp/test.png to the browser. Of course, you first need to save the image to this location.
Our team will make some modifications to requestHandlers.js:
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 image saved in /tmp/test.png by visiting http://localhost:8888/show.
Okay, the last thing we want is:
Add a file upload element to the /start form
Integrate node-formidable into our upload request handler for saving uploaded images to /tmp/test.png
Embed the uploaded image into the HTML output by /uploadURL
The first item is simple. Just 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 requestHandler.js below:
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" />'
''
''
'
'method="post">'
''
''
''
''
'';
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 have to complete the second step. We start with server.js - remove the processing of postData and request.setEncoding (this part node-formidable will handle it itself), and instead pass the request object to How to request routing:
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 handler. node-formidable will handle saving the uploaded file to the local /tmp directory, and we need to
What to do is make sure the file is saved as /tmp/test.png.
Next, we put together the operations of processing file uploads and renaming, as shown in requestHandlers.js below:
var querystring = require("querystring"),
fs = require("fs"),
formidable = require("formidable");
function start(response) {
console.log("Request handler 'start' was called.");
var body = ''
''
''
''
''
'
'method="post">'
''
''
''
''
'';
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;
After doing this, our server is complete.
During the process of uploading images, some people may encounter the following problems:
I guess the cause of this problem is caused by disk partition. To solve this problem, you need to change the default zero-time folder path of formidable to ensure that it is in the same disk partition as the target directory.
We find the upload function of requestHandlers.js and make some modifications to it:
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
We added the sentence form.uploadDir = “tmp”, now restart the server, and then perform the upload operation, the problem is perfectly solved.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn