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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools
