1.安装
cnpm install multer --save
2.单文件上传
moudel/tools.js
const path= require("path");const multer = require("multer");let tools = {multer(){const storage = multer.diskStorage({// 配置上传的目录destination: fuction(req, file, callback){callback(null, "static/upload"); // 自定义保存路径},// 修改上传后的文件名filename: fuction(req, file, callback){// 1.获取后缀名let extName = path.extname(file.originalname);// 2.根据时间戳生成文件名callback(null, file.filename + "-" + Date.now() + extName)}}); const upload = multer({storage: storage});return upload}}module.exports = tools;
app.js
const express = require("express");const tools = require("./module/tools");const app = express();app.post('/profile', tools.multer().single("avatar"), fuction(req, res){res.send(req.file.originalname);})
form.html
<form action="/profile" method="post", enctype="multipar/form-data"><input type="file" name="avatar"></form>
3.根据日期生成目录
const sd = require("silly-datetime");const mkdirp = require("mkdirp");const storage = multer.diskStorage({// 配置上传的目录destination: async (req, file, callback){// 1.获取当前日期let day = sd.format(new Date, "YYYYMMDD");// 2.按照日期生成图片存储目录let dir = path.join("static/upload", day);await mkdirp(dir); // 异步方法callback(null, dir); // 自定义保存路径},// 修改上传后的文件名filename: fuction(req, file, callback){// 1.获取后缀名let extName = path.extname(file.originalname);// 2.根据时间戳生成文件名callback(null, file.filename + "-" + Date.now() + extName)}}); const upload = multer({storage: storage});
4.多文件上传
app.js
const express = require("express");const tools = require("./module/tools");const app = express();const cpUpload = tools.multer().fields([{name: 'avatar1', maxCount: 1 }, {name: 'avatar2', maxCount: 1 }])app.post('/profile', cpUpload, fuction(req, res){res.send(req.files);})
<form action="/profile" method="post", enctype="multipar/form-data"><input type="file" name="avatar1"><input type="file" name="avatar2"></form>