Let's talk about how node+multiparty implements file uploading
How to upload files using node? The following article will introduce to you how to upload files using node combined with multiparty. I hope it will be helpful to you!
File uploading is probably an essential operation in every project. Today we use nodejs to implement a file upload module.
1.Module
npm i multiparty
npm i express
2.Code
We put the code in the (upload.js
) file. The code in the file is as follows:
// 上传文件模块 const multiparty = require('multiparty') // 文件操作模块 const fs = require('fs') // 导入express框架 const express = require('express') // 路由 const router = express.Router() // 上传文件接口 router.post('/upload/file', (req, res) => { /* 生成multiparty对象,并配置上传目标路径 */ let form = new multiparty.Form(); // 设置编码 form.encoding = 'utf-8'; // 设置文件存储路径,以当前编辑的文件为相对路径 form.uploadDir = './public'; // parse,表单解析器 // fields :普通的表单数据 // files:上传的文件的信息 form.parse(req, function (err, fields, files) { try { // 文件为files.file[0] let upfile = files.file[0] // 为文件进行命名,修改upfile文件中的path,否则会随机生成文件名 let newpath = form.uploadDir + '/' + upfile.originalFilename //文件名 // 重命名 fs.renameSync(upfile.path, newpath); // 返回信息,((upfile.size)/1048576).toFixed(2)将文件由B转换为M的单位并进行取小数点后两位进行四舍五入向上取操作 res.send({ code:200, msg:'File Success', file_name:upfile.originalFilename, file_size:((upfile.size)/1048576).toFixed(2)+'M' }) } catch { // 异常情况下的消息 console.log(err) res.send({ code:401, msg:'File error', more_msg:err }) } }) }) // 导出该模块供main主函数文件中进行调用 module.exports = router
##3.main .js file
// 引入express模块 const express = require('express') // 实例化express const app = express() // 文件夹映射 app.use('/static',express.static('public')) // 上传文件接口 const upload=require('./router/upload') app.use(upload) // 监听服务 app.listen('3333', '0.0.0.0', (res) => { console.log('Server running http://127.0.0.1:3333') })
4. Example
Call it done
nodejs tutorial!
The above is the detailed content of Let's talk about how node+multiparty implements file uploading. 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.

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.

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.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

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.

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.
