国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
上傳單個文件
上傳多個文件
將文件部署為靜態(tài)資源
Home Web Front-end JS Tutorial How 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
nodejs node express File 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('服務(wù)器開啟')
})

引入后的 multer 為一個函數(shù),執(zhí)行它得到 upload 對象,執(zhí)行時可以傳入配置,比如設(shè)置 dest (destination 的縮寫) 為 './uploads',用于指定上傳后的文件的存放位置: 【相關(guān)教程推薦:nodejs視頻教程、編程教學(xué)

const upload = multer({ dest: './uploads' })

由于對上傳文件的處理并不是普遍需要的,所以對 upload 的使用是直接在匹配上傳路徑(我們定義為 '/upload')和方法(一般為 POST)的 app.post('/upload', ) 內(nèi),處理的是單個文件上傳,所以使用 upload.single() 方法,傳入的 'file'(自定義,也可以為其它名字) 為上傳文件時的 key:

How to use express to handle file upload in node project

其執(zhí)行會返回一個中間件函數(shù),將得到的文件的數(shù)據(jù)賦值到 req.file,而文本字段的信息則會放在 req.body 中,并調(diào)用 next(),這樣我們就可以接著注冊一個中間件,打印查看文件信息,并向客戶端返回請求結(jié)果 :

app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.body)
  console.log(req.file)
  res.end('上傳成功')
})

發(fā)起上傳請求后,打印得到的 req.body 如下:

[Object: null prototype] { name: 'jay' }

注意,如果請求的 body 使用 form-data 格式攜帶的數(shù)據(jù)里沒有文件,而僅僅是一些文本字段,則 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 是可以直接打開查看的。那如果想讓文件存儲時的文件名是添加后綴的,要怎么辦呢?解決方案是在執(zhí)行 const upload = multer() 時,傳入的配置對象不再設(shè)置 dest 的值而改為設(shè)置 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() 生成,其內(nèi)部傳入對象,該對象有兩個方法屬性,它們都有 3 個參數(shù),請求對象 req,文件信息 file,和一個回調(diào)函數(shù) cb

  • destination 就是配置文件存儲路徑的,其作用等同于之前直接往 multer() 傳入的 { dest: './uploads' },存儲路徑通過 cb 的第二個參數(shù)傳入,cb 的第一個參數(shù)可以傳 Error 對象或直接傳 null
  • filename 就可以用來自定義文件名,因為 file.originalname 也就是上傳的文件的原來的文件名,其是帶有后綴的,所以我們在它前面加個時間戳來作為存儲時的文件名。

現(xiàn)在再次發(fā)送上傳文件請求,存儲到 uploads 目錄下的文件就有帶后綴名了,可以直接在 vscode 打開查看:

How to use express to handle file upload in node project

上傳多個文件

如果請求一次性上傳多個文件,則只需要將 upload.single('file') 替換為 upload.array('files', 3) 即可,傳入?yún)?shù)意為上傳時文件的 key 為 files(自定義的,也可以是其它名字),并且限制最多上傳 3 張圖片,得到的文件信息可以在下一個中間件函數(shù)的 req.files 獲取:

app.post('/upload', upload.array('files', 3), (req, res) => {
  console.log(req.files)
  res.end('上傳成功')
})

當(dāng)我們一次上傳多個文件時:

How to use express to handle file upload in node project

打印 req.files 得到的就是個數(shù)組了:

[
  {
    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
  }
]

將文件部署為靜態(tài)資源

可以使用內(nèi)置的 express.static('./uploads') 中間件函數(shù)將存儲上傳文件的 uploads 目錄設(shè)置為靜態(tài)資源。然后傳給 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相關(guān)知識,請訪問: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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

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.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

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.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

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

Can nodejs write front-end? Can nodejs write front-end? Apr 21, 2024 am 05:00 AM

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

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

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

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.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

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.

What projects is nodejs suitable for? What projects is nodejs suitable for? Apr 21, 2024 am 05:45 AM

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices

See all articles