Nodejs+express makes file upload
This time I will bring you nodejs express to upload files. What are the precautions for nodejs express to upload files? The following is a practical case, let’s take a look.
The example in this article describes how nodejs implements file upload based on express. I would like to share it with you for your reference. The details are as follows:
When I was working on a personal project some time ago, I used the nodejs server to upload files. Now I will summarize this as a record.
When I upload files, I use express's multiparty. Of course, it can also be implemented using the connect-multiparty middleware, but the official does not seem to recommend the use of connect-multiparty middleware. Without further ado, let’s look at the code below.
Steps:
(1) Use express to create a project. The jade template engine is used by default, but I am still used to html, so I changed it to html template.
(2) In the project directory, install the necessary components through npm install multiparty.
(3) Modify views/index.html and add a file upload form.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> 上传文件 <form method='post', action='/file/uploading', enctype='multipart/form-data'> <input type="file" name="inputFile"> <input type="submit" value="上传"> </form> </body> </html>
(4) Modify routes/index.js to implement the background code for uploading pages and uploading responses.
var express = require('express'); var router = express.Router(); var multiparty = require('multiparty'); var util = require('util'); var fs = require('fs'); /* 上传页面. */ router.get('/', function(req, res, next) { //res.render('./views/index'); res.sendfile('./views/index.html'); }); /* 上传 */ router.post('/file/uploading', function(req, res, next) { /* 生成multiparty对象,并配置上传目标路径 */ var form = new multiparty.Form(); /* 设置编辑 */ form.encoding = 'utf-8'; //设置文件存储路劲 form.uploadDir = './public/files'; //设置文件大小限制 form.maxFilesSize = 2 * 1024 * 1024; // form.maxFields = 1000; //设置所有文件的大小总和 //上传后处理 form.parse(req, function(err, fields, files) { var filesTemp = JSON.stringify(files, null, 2); if(err) { console.log('parse error:' + err); }else { console.log('parse files:' + filesTemp); var inputFile = files.inputFile[0]; var uploadedPath = inputFile.path; var dstPath = './public/files' + inputFile.originalFilename; //重命名为真实文件名 fs.rename(uploadedPath, dstPath, function(err) { if(err) { console.log('rename error:' + err); }else { console.log('rename ok'); } }) } res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields, files: filesTemp})) }) }) module.exports = router;
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
ip cannot access vue webpack myproject how to deal with it
vue-cli webpack cannot create a new project
preload() function and image upload use
The above is the detailed content of Nodejs+express makes file upload. For more information, please follow other related articles on the PHP Chinese website!

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

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

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.

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

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.
