- Multer 是一個(gè) node.js 中間件,用于處理
multipart/form-data
類型的表單數(shù)據(jù),它主要用于上傳文件。它是寫在 busboy 之上的所以非常高效。 - 前面我們已經(jīng)知道了怎樣利用express提供的靜態(tài)資源處理中間件
express.static()
處理用戶請(qǐng)求靜態(tài)資源文件(圖片, js, css等) 接下來(lái)學(xué)習(xí)如何處理用戶上傳文件, 編寫處理上傳文件的接口 (以圖片為例) - 下面就直接上代碼
const http = require('http');
const fs = require('fs');
const path = require('path');
const express = require('express');
const multer = require('multer');
const app = express();
app.use(express.json());
//文件上傳
//https://github.com/expressjs/multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadFile = req.params['upload_file'];
const filename = path.join(__dirname, `./upload/${uploadFile}`);
fs.existsSync(filename) || fs.mkdirSync(filename);
cb(null, filename);
},
filename: (req, file, cb) => {
console.log(file);
let saveName = req.params['saveName'] || Date.now();
let extName = path.extname(file.originalname || '.jpg');
cb(null, saveName + '-' + Date.now() + extName);
}
});
const upload = multer({ storage: storage });
//express中間件的洋蔥模型
app.use('/', (req, res, next) => {
console.log('根路由');
next();
console.log('根路由 洋蔥穿透');
});
app.use('/user', (req, res, next) => {
console.log('用戶路由');
next();
console.log('用戶路由 洋蔥穿透');
});
//用戶可以指定要保存在哪個(gè)文件夾(不存在則創(chuàng)建) 和 保存的文件名
app.use(
'/user/:upload_file/:saveName',
(req, res, next) => {
console.log('上傳路由');
next();
console.log('上傳路由 洋蔥穿透');
},
upload.array('file'),
(req, res, next) => {
console.log(req.headers['content-type'], req.body);
res.send({ msg: 'upload success !' });
next();
}
);
const server = http.createServer(app);
server.listen(3010, () => {
console.log('listening...');
});
- 用
postmen
測(cè)試一下就可以啦, 注意請(qǐng)求的數(shù)據(jù)類型應(yīng)該是multipart/form-data
- 上面的代碼還提到了express中間件的洋蔥模型
輸出順序是:
根路由
用戶路由
上傳路由
上傳路由 洋蔥穿透
用戶路由 洋蔥穿透
根路由 洋蔥穿透
這是express中間件的重要機(jī)制, 邏輯上比較像dom事件的捕獲與冒泡階段文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-737964.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-737964.html
到了這里,關(guān)于node 第十四天 基于express的第三方中間件multer node后端處理用戶上傳文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!