本章将学习Express multer 文件上传 ,因为Nest 的文件上传是基于 Express 的中间件 multer 实现的,所以在学习 Nest 文件上传之前,我们先学习下 multer 包
首先先创建 multer-test 文件夹
执行下面代码 创建package.json
npm init -y
接着安装 express 和 multer 还有 cors 包:
npm install express multer cors
创建index.js 并修改:
const express = require('express')
const multer = require('multer')
const cors = require('cors');const app = express()
app.use(cors());const upload = multer({ dest: 'uploads/' })app.post('/aaa', upload.single('aaa'), function (req, res, next) {console.log('req.file', req.file);console.log('req.body', req.body);
})app.listen(5200);
app.use 使用中间件 cors 来处理跨域。
用 multer 处理文件上传,指定保存目录为 uploads/。
接着新建index.html:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head><body><input id="fileInput" type="file" /><script>const fileInput = document.querySelector('#fileInput');async function formData() {const data = new FormData();data.set('name', '光');data.set('age', 20);data.set('aaa', fileInput.files[0]);const res = await axios.post('http://localhost:5200/aaa', data);console.log(res);}fileInput.onchange = formData;</script>
</body></html>
使用FormData + axios 上传文件,指定内容的传输格式 content-type 为 multipart/form-data。
用 node 把 server 跑起来,并且用 http-server 把静态服务跑起来
游览器访问 http://192.168.100.222:8080/
接着点击选择文件 上传文件 看游览器的控制台 可以看到发送了请求 此时aaa 请求的 body 是多个 boundary 分隔的格式
分隔符是在 Content-Type 指定的
这是 form-data 的传输格式
接着我们在控制端可以看到服务端打印了信息
服务端多了 uploads 目录,下面就保存着我们上传的文件:
我们再实现多文件上传 修改index.js
const express = require('express')
const multer = require('multer')
const cors = require('cors');const app = express()
app.use(cors());const upload = multer({ dest: 'uploads/' })app.post('/aaa', upload.single('aaa'), function (req, res, next) {console.log('req.file', req.file);console.log('req.body', req.body);
})app.post('/bbb', upload.array('bbb',2), function (req, res, next) {console.log('req.files', req.files);console.log('req.body', req.body);
})app.listen(5200);
再次修改index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head>
<body><input id="fileInput" type="file" multiple/><script>const fileInput = document.querySelector('#fileInput');async function formData2() {const data = new FormData();data.set('name','光');data.set('age', 20);[...fileInput.files].forEach(item => {data.append('bbb', item)})const res = await axios.post('http://localhost:5200/bbb', data);console.log(res);}fileInput.onchange = formData2;</script>
</body>
</html>
input 标签添加 multiple 属性允许多选。
onchange 的时候取出每个 file,通过 append 方法添加到 bbb 字段
可以看到上传的是一个数组,并且 uploads 目录下也多了俩文件
接着我们在express 里添加错误中间件,一旦某个中间件出了错,express 就会向后找错误处理中间件来调用,如果没有,那就用默认错误处理中间件,返回 500 响应。
const express = require('express')
const multer = require('multer')
const cors = require('cors');const app = express()
app.use(cors());const upload = multer({ dest: 'uploads/' })app.post('/aaa', upload.single('aaa'), function (req, res, next) {console.log('req.file', req.file);console.log('req.body', req.body);
})app.post('/bbb', upload.array('bbb', 2), function (req, res, next) {console.log('req.files', req.files);console.log('req.body', req.body);
}, function (err, req, res, next) {console.log('err', err);
})app.listen(5200);
接着我们上传超过2个文件:
可以看到服务端显示了错误,我们再改造一下即可返回错误信息
const express = require('express')
const multer = require('multer')
const cors = require('cors');const { MulterError } = multer; const app = express()
app.use(cors());const upload = multer({ dest: 'uploads/' })app.post('/aaa', upload.single('aaa'), function (req, res, next) {console.log('req.file', req.file);console.log('req.body', req.body);
})app.post('/bbb', upload.array('bbb', 2), function (req, res, next) {console.log('req.files', req.files);console.log('req.body', req.body);
}, function(err, req, res, next) {if(err instanceof MulterError && err.code === 'LIMIT_UNEXPECTED_FILE') {res.status(400).end('Too many files uploaded');}
})app.listen(5200);
传超过 2 个文件,就会收到服务端的 400 的响应:
我们尝试多字段上传
const express = require('express')
const multer = require('multer')
const cors = require('cors');const { MulterError } = multer; const app = express()
app.use(cors());const upload = multer({ dest: 'uploads/' })app.post('/aaa', upload.single('aaa'), function (req, res, next) {console.log('req.file', req.file);console.log('req.body', req.body);
})app.post('/bbb', upload.array('bbb', 2), function (req, res, next) {console.log('req.files', req.files);console.log('req.body', req.body);
}, function(err, req, res, next) {if(err instanceof MulterError && err.code === 'LIMIT_UNEXPECTED_FILE') {res.status(400).end('Too many files uploaded');}
})app.post('/ccc', upload.fields([{ name: 'aaa', maxCount: 3 },{ name: 'bbb', maxCount: 2 }
]), function (req, res, next) {console.log('req.files', req.files);console.log('req.body', req.body);
})app.listen(5200);
通过 fields 方法指定每个字段的名字和最大数量,接收到请求后通过 req.files[‘xxx’] 来取对应的文件信息,其他非文件字段,同样是通过 req.body 来取
修改index.html代码:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head><body><input id="fileInput" type="file" multiple /><script>const fileInput = document.querySelector('#fileInput');async function formData2() {const data = new FormData();data.set('name', '光');data.set('age', 20);[...fileInput.files].forEach(item => {data.append('bbb', item)})const res = await axios.post('http://localhost:5200/bbb', data);console.log(res);}async function formData3() {const data = new FormData();data.set('name', '光');data.set('age', 20);data.append('aaa', fileInput.files[0]);data.append('aaa', fileInput.files[1]);data.append('bbb', fileInput.files[2]);data.append('bbb', fileInput.files[3]);const res = await axios.post('http://localhost:5200/ccc', data);console.log(res);}fileInput.onchange = formData3;</script>
</body></html>
可以看到服务端上传了4个新的文件