1、routers 文件夹下新建 upload.js 文件
const express = require('express');
const router = express.Router();
const multer = require('multer');
let upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var changedName = (new Date().getTime())+'-'+file.originalname;
cb(null, changedName);
}
})
});
//单个文件上传
router.post('/single', upload.single('singleFile'), (req, res) => {
console.log(req.file);
res.json({
code: '0000',
type: 'single',
originalname: req.file.originalname,
path: req.file.path
})
});
//多个文件上传
router.post('/multer', upload.array('multerFile'), (req, res) => {
console.log(req.files);
let fileList = [];
req.files.map((elem) => {
fileList.push({
originalname: elem.originalname
})
});
res.json({
code: '0000',
type: 'multer',
fileList: fileList
});
});
module.exports = router;
2、在项目根目录下创建 uploads 文件夹
3、app.js 引入改文件并使用
//引入路由
const multerUpload = require('./routes/upload');
//使用路由
app.use('/upload', multerUpload);
4、在 views 文件夹下 创建 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- 单文件上传 -->
<div class="single">
<div class="title">单个文件上传</div>
<input type="file" name="singleFile" id="singleFile">
<button class="submit">上传</button>
<img src="" alt="" id="img">
</div>
<div class="multer">
<div class="title">多个文件上传</div>
<input type="file" name="multerFile" id="multerFile" multiple>
<button class="submit">上传</button>
</div>
<div class="upbefore">
<div class="title">可多次点击添加按钮,并预览</div>
<div id="imgs"></div>
<input type="file" id="upgteimg" value=""/>
<button class="submit">上传</button>
</div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
// 单文件上传
$('.single .submit').on('click', function () {
var fileList = $('#singleFile')[0].files;
console.log(fileList);
var formData = new FormData();
//此处文件名必须为 singleFile ,因为后台设置仅接口此文件名
formData.append('singleFile', fileList[0]);
$.ajax({
url: '/upload/single',
type: 'post',
processData: false,
contentType: false,//使用multer配合ajax时无需配置multipart/form-data,multer将自动配置,手动配置将报错,boundary not found
data: formData,
success: function (data) {
console.log(data)
$('#img').attr('src', data.path)
}
})
});
// 多文件上传
$('.multer .submit').on('click', function () {
var fileList = $('#multerFile')[0].files;
console.log(fileList);
var formData = new FormData();
for (let i = 0; i < fileList.length; i++) {
//此处文件名必须为 multerFile ,因为后台设置仅接口此文件名
formData.append('multerFile', fileList[i]);
}
$.ajax({
url: '/upload/multer',
type: 'post',
processData: false,
contentType: false,
data: formData,
success: function (data) {
console.log(data)
}
})
});
// 可多次点击添加按钮,并预览
let arr = [];
let src = [];
$('#upgteimg').on('change', function () {
let $this = $(this)
let url = URL.createObjectURL($this[0].files[0]);
src.push(url);
arr.push($this[0].files[0]);
console.log(arr);
console.log(src);
showImg()
})
function showImg() {
let html = ''
for (let i = 0; i < src.length; i++) {
const element = src[i];
html += `<img src="${element}" alt="">`
}
$('#imgs').html(html);
}
$('.upbefore .submit').on('click', function () {
var formData = new FormData();
for (let i = 0; i < arr.length; i++) {
//此处文件名必须为 multerFile ,因为后台设置仅接口此文件名
formData.append('multerFile', arr[i]);
}
$.ajax({
url: '/upload/multer',
type: 'post',
processData: false,
contentType: false,
data: formData,
success: function (data) {
console.log(data)
}
})
})
</script>
</body>
</html>
在这我们对上传做了一些限制:
const express = require('express');
const router = express.Router();
const multer = require('multer');
let upload = multer({
limits:{
//限制文件大小10kb
fileSize: 10*1000,
//限制文件数量
files: 5
},
storage: multer.diskStorage({
destination: function (req, file, cb) {
// if (file) {
cb(null, './uploads/');
// }
},
filename: function (req, file, cb) {
// if (file) {
var changedName = (new Date().getTime())+'-'+file.originalname;
cb(null, changedName);
// }
}
}),
fileFilter: function(req, file, cb){
// 限制文件上传类型,仅可上传png格式图片
if(file.mimetype == 'image/png'){
cb(null, true)
} else {
cb(null, false)
}
}
});
let singleUpload = upload.single('singleFile');
//单个文件上传
router.post('/single',(req,res)=>{
singleUpload(req,res,(err)=>{
if(!!err){
console.log(err.message)
res.json({
code: '2000',
type:'single',
originalname: '',
msg: err.message
})
return;
}
if(!!req.file){
res.json({
code: '0000',
type:'single',
originalname: req.file.originalname,
msg: ''
})
} else {
res.json({
code: '1000',
type:'single',
originalname: '',
msg: ''
})
}
});
});
let multerUpload = upload.array('multerFile');
//多个文件上传
router.post('/multer', (req,res)=>{
multerUpload(req,res,(err)=>{
if(!!err){
res.json({
code: '2000',
type:'multer',
fileList:[],
msg: err.message
});
}
let fileList = [];
req.files.map((elem)=>{
fileList.push({
originalname: elem.originalname
})
});
res.json({
code: '0000',
type:'multer',
fileList:fileList,
msg:''
});
});
});
module.exports = router;
这里面可以看到,对文件大小和类型做了相应限制,文件过大的话会进入err,文件类型不对的话不会进 err
upload.single('key值'):当传递单个文件的时候,对文件的解析
upload.array('key值', maxCout):当传递一组文件的时候,对文件的解析 key值是前端传递的key值 maxcout是最多能传递多少个文件
upload.fields([{ name: 'key值', maxCount: num }, { name: 'key值', maxCount: num }]):当传递多个文件域的时候,对文件的解析