node: express parses multipart/form-data data; uploads files (single file + multiple files)

Table of contents

foreword

download

use

Single file upload:

Multiple file upload

result


foreword

When uploading files, we will use the multipart/form-data request body format, and the express.urlencoded() middleware cannot parse data in this format, so we need to find a format that can parse multipart/form-data Package, multer is recommended here, npm address : multer - npm

download

npm install --save multer

use

 Single file upload:

  In order to make it easier to interpret the code, there is no modular approach here

const express = require('express');
const router = express.Router();
const multer = require('multer')
const path = require('path')
const upload = multer({dest: path.join(__dirname, '../../uploads')}) // 要存放文件的路径

router.post('/api/upload/file', upload.single('image'), (req, res) => {
    console.log(req.body)
    console.log(req.file)
    res.send('success')
})

module.exports = router

Request testing with postman

 Print result:

 In this way, we get the information of the uploaded file and the additional parameters we passed

Multiple file upload

//注意看取值变量
router.post('/api/upload/files', upload.array('image'), (req, res) => {
    console.log(req.body)
    console.log(req.files)
    res.send('success')
})

postman request test

 Console prints:

result

We can see the uploads directory in the project, which contains the files we upload. According to your own project, where are the uploads?

Guess you like

Origin blog.csdn.net/qq_42543244/article/details/126627944