Easily create a nodejs server (10): handle uploaded images_node.js
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:
npm install formidable
If similar information is output, the installation is successful:
npm info build Success: formidable@1.0.14
After the installation is successful, we can use request to introduce it:
var formidable = require(“formidable”);
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 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 route map in index.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:
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 passing the request object:
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");
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 the sentence form.uploadDir = “tmp”, now restart the server, and then perform the upload operation, the problem is perfectly solved.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.
