How to use express to handle file upload in node project
怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!
上传单个文件
我们可以使用 express 官方出品的第三方中间件 multer 来处理,先是安装:
npm i multer
然后我先放段比较完整的代码,之后解释:
const express = require('express') const multer = require('multer') const app = express() const upload = multer({ dest: './uploads' }) app.post('/upload', upload.single('file'), (req, res) => { console.log(req.file) res.end('上传成功') }) app.listen(4396, () => { console.log('服务器开启') })
引入后的 multer
为一个函数,执行它得到 upload
对象,执行时可以传入配置,比如设置 dest
(destination 的缩写) 为 './uploads'
,用于指定上传后的文件的存放位置: 【相关教程推荐:nodejs视频教程、编程教学】
const upload = multer({ dest: './uploads' })
由于对上传文件的处理并不是普遍需要的,所以对 upload
的使用是直接在匹配上传路径(我们定义为 '/upload'
)和方法(一般为 POST)的 app.post('/upload', )
内,处理的是单个文件上传,所以使用 upload.single()
方法,传入的 'file'
(自定义,也可以为其它名字) 为上传文件时的 key:
其执行会返回一个中间件函数,将得到的文件的数据赋值到 req.file
,而文本字段的信息则会放在 req.body
中,并调用 next()
,这样我们就可以接着注册一个中间件,打印查看文件信息,并向客户端返回请求结果 :
app.post('/upload', upload.single('file'), (req, res) => { console.log(req.body) console.log(req.file) res.end('上传成功') })
发起上传请求后,打印得到的 req.body
如下:
[Object: null prototype] { name: 'jay' }
注意,如果请求的 body 使用 form-data
格式携带的数据里没有文件,而仅仅是一些文本字段,则 upload.single('file')
可以换成 upload.any()
。
打印得到的 req.file
如下:
{ fieldname: 'file', originalname: 'How to use express to handle file upload in node project', encoding: '7bit', mimetype: 'image/png', destination: './uploads', filename: '4c5781db70269d90cc57249e95a28894', path: 'uploads\\4c5781db70269d90cc57249e95a28894', size: 904454 }
并且文件会存储在 uploads 目录下:
可以看到,文件名为哈希值,且没有后缀,在 vscode 里无法直接查看图片:
但图片文件是可用的,使用 ps 是可以直接打开查看的。那如果想让文件存储时的文件名是添加后缀的,要怎么办呢?解决方案是在执行 const upload = multer()
时,传入的配置对象不再设置 dest
的值而改为设置 storage
:
const storage = multer.diskStorage({ destination(req, file, cb) { cb(null, './uploads') }, filename(req, file, cb) { cb(null, Date.now() + '-' + file.originalname) } }) const upload = multer({ storage })
storage
对象由 multer.diskStorage()
生成,其内部传入对象,该对象有两个方法属性,它们都有 3 个参数,请求对象 req
,文件信息 file
,和一个回调函数 cb
:
destination
就是配置文件存储路径的,其作用等同于之前直接往multer()
传入的{ dest: './uploads' }
,存储路径通过 cb 的第二个参数传入,cb 的第一个参数可以传 Error 对象或直接传null
;filename
就可以用来自定义文件名,因为file.originalname
也就是上传的文件的原来的文件名,其是带有后缀的,所以我们在它前面加个时间戳来作为存储时的文件名。
现在再次发送上传文件请求,存储到 uploads 目录下的文件就有带后缀名了,可以直接在 vscode 打开查看:
上传多个文件
如果请求一次性上传多个文件,则只需要将 upload.single('file')
替换为 upload.array('files', 3)
即可,传入参数意为上传时文件的 key 为 files(自定义的,也可以是其它名字),并且限制最多上传 3 张图片,得到的文件信息可以在下一个中间件函数的 req.files
获取:
app.post('/upload', upload.array('files', 3), (req, res) => { console.log(req.files) res.end('上传成功') })
当我们一次上传多个文件时:
打印 req.files
得到的就是个数组了:
[ { fieldname: 'files', originalname: 'How to use express to handle file upload in node project', encoding: '7bit', mimetype: 'image/png', destination: './uploads', filename: '1676958850980-How to use express to handle file upload in node project', path: 'uploads\\1676958850980-How to use express to handle file upload in node project', size: 904454 }, { fieldname: 'files', originalname: 'qrcode.png', encoding: '7bit', mimetype: 'image/png', destination: './uploads', filename: '1676958850986-qrcode.png', path: 'uploads\\1676958850986-qrcode.png', size: 1076 } ]
将文件部署为静态资源
可以使用内置的 express.static('./uploads')
中间件函数将存储上传文件的 uploads 目录设置为静态资源。然后传给 app.use()
:
app.use(express.static('./uploads'))
这样我们就可以直接通过浏览器查看上传得到的文件了,比如 uploads 有张图片如下:
只需要在浏览器输入 localhost:4396/1677031777791-How to use express to handle file upload in node project 即可查看。
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of How to use express to handle file upload in node project. 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.

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 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

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.

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

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.
