search
HomeWeb Front-endJS TutorialHow to use express to handle file upload in node project

How to use express to handle file upload in node project

Mar 28, 2023 pm 07:28 PM
nodejsnodeexpressFile Upload

怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!

How to use express to handle file upload in node project

上传单个文件

我们可以使用 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:

How to use express to handle file upload in node project

其执行会返回一个中间件函数,将得到的文件的数据赋值到 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 目录下:

How to use express to handle file upload in node project

可以看到,文件名为哈希值,且没有后缀,在 vscode 里无法直接查看图片:

How to use express to handle file upload in node project

但图片文件是可用的,使用 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 打开查看:

How to use express to handle file upload in node project

上传多个文件

如果请求一次性上传多个文件,则只需要将 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('上传成功')
})

当我们一次上传多个文件时:

How to use express to handle file upload in node project

打印 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 有张图片如下:

How to use express to handle file upload in node project

只需要在浏览器输入 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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function