multer中间件上传文件
上传图片中间件 multer
//1.基本语法
npm i multer -S
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
filename: function (req, file, cb) {
console.log(file)
let originalName = file.originalname;
let ext = originalName.split('.');
ext= ext[ext.length-1]
cb(null, file.fieldname + '-' + Date.now()+'.'+ext)
}
})
const upload = multer({ storage: storage })
router.post('/upload',upload.single('img'),(req,res)=>{
res.send({
code:0,
msg:"上传成功"
})
})
2.html中form表单中传输文件一定要加入enctype=“multipart/formdata”
<form action="" method="post" enctype="multipart/formdata">
<input/>
</form>
实例
创建upload.js upload.ejs app.js uploads(接收图片)
npm i express body-parser ejs multer -S
首先:在app.js中
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express()
const uploadRouter = require('./routes/upload');
const { urlencoded } = require('body-parser');
//设置post解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}))
//设置views
app.set("views",path.join(__dirname,"/views"))
app.set("view engine","ejs")
//使用上传中间件
app.use(uploadRouter)
app.listen(3210,()=>{
console.log("start at port 3210")
})
2,upload.js中
const router = require('express').Router();
const multer = require('multer')
const storage = multer.diskStorage({
//有两个函数,第一个函数是定义存储位置,需要提前创建好文件夹,第二个函数定义文件名.
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
filename: function (req, file, cb) {
console.log(file)
// 处理文件后缀名
let fileArr = file.originalname.split('.')
cb(null, file.fieldname + '-' + Date.now()+'.'+fileArr[fileArr.length-1])
}
})
const upload = multer({ storage: storage })
//首先获取下载页面
router.get("/upload",(req,res)=>{
res.render("upload")
})
//上传文件的路由,三个参数,中间参数的参数是上传文件的name值
router.post("/upload",upload.single('img'),(req,res)=>{
res.send({
code:0,
msg:'上传成功'
})
})
module.exports = router
3.upload.ejs文件内容用来传输post数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href=" ">
<link rel="stylesheet" href=" ">
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<!--数以传输文件时必须要加enctype,文件输入框要加name属性-->
<input type="file" name="img" id='file'>
<img src="" alt="" id="img">
<input type="submit" value="提交">
</form>
</body>
<script type="text/javascript" src="" ></script>
<script type="text/javascript">
</script>
</html>
封装upload
1.一般新建文件夹utils存放自己封装的模块,创建upload.js
const multer = require('multer')
const storage = multer.diskStorage({
//有两个函数,第一个函数是定义存储位置,需要提前创建好文件夹,第二个函数定义文件名.
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
filename: function (req, file, cb) {
console.log(file)
// 处理文件后缀名
let fileArr = file.originalname.split('.')
cb(null, file.fieldname + '-' + Date.now()+'.'+fileArr[fileArr.length-1])
}
})
const upload = multer({ storage: storage })
//导出
module.exports = upload
2.routes中upload文件引入
const router = require('express').Router();
//引入封装好的上传文件,注意路径需要../,这里是router目录下的文件引入使用的
const upload = require('../utils/upload.js');
//首先获取下载页面
router.get("/upload",(req,res)=>{
res.render("upload")
})
//上传文件的路由,三个参数,中间参数的参数是上传文件的name值
router.post("/upload",upload.single('img'),(req,res)=>{
res.send({
code:0,
msg:'上传成功'
})
})
module.exports = router
3.upload.ejs中上传图片预览
<script>
var file = document.querySelector('#file');
var oImg = document.querySelector('#img')
file.onchange = function(){
// 有个files属性
console.log(this.files[0])
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
//异步操作,需要监听
reader.onload = function(){
// 监听 reader 读取文件的进度,当读取完毕时触发
console.log(this.result)
oImg.src = this.result
}
}
</script>