前端部分,采用了拖拽文件的上传方式:
<el-upload
class="upload-demo"
drag
:action="uploadUrl"
:limit="10"
:on-exceed="handleExceed"
multiple
:on-success="handleUploadSuccess"
accept=".jpg, .jpeg, .png"
ref="uploadDom"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">每次最多10个文件</div>
</el-upload>
前端对应的事件
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择 10 个文件,本次选择了 ${
files.length
} 个文件,共选择了 ${files.length + fileList.length} 个文件`
);
},
handleUploadSuccess(doc) {
if (doc.code == 0) {
this.tableData.push(doc.data[0]);
} else {
this.$message({
type: "error",
message: doc.msg
});
}
this.$refs.uploadDom.clearFiles();
}
后端接受事件
let multer = require('multer');
let fs = require("fs");
let path = require("path");
router.post('/upload', multer({
//设置文件存储路径
dest: songUploadPath //upload文件如果不存在则会自己创建一个。
}).array('file', 10), function (req, res, next) {
let files = req.files;
if (files.length === 0) {
res.json({
code: 1,
msg: "上传文件不能为空!",
data: null
});
return
} else {
let fileInfos = [];
files.forEach(item => {
let fileInfo = {};
fs.renameSync(songUploadPath + item.filename, songUploadPath + item.originalname); //这里修改文件名。
//获取文件基本信息
//去掉后缀
let index = item.originalname.lastIndexOf(".")
fileInfo.songName = item.originalname.substring(0, index);
// fileInfo.size = item.size;
fileInfo.url = '/music/' + item.originalname;
fileInfos.push(fileInfo);
})
songDao.addData(fileInfos, (doc) => {
if (doc.code == 0) {
let resData = [];
doc.data.forEach((o, index) => {
detailDao.addData({
songId: o._id,
singerId: null,
albumId: null
}, newDoc => {
if (newDoc.code == 0) {
detailDao.findDataById(newDoc.data._id, detailDoc => {
resData.push(detailDoc.data);
if (index == doc.data.length - 1) {
console.log(doc.data, resData);
if (doc.data.length == resData.length) {
res.json({
code: 0,
msg: '添加成功',
data: resData
})
} else {
res.json({
code: 1,
msg: '并未全部添加成功',
data: resData
})
}
}
})
} else {
//回滚机制,理论上删除即可
songDao.deleteDataById(o._id, () => {
res.json(detailDoc)
})
}
})
})
} else {
res.json(doc)
}
})
}
})
还有记得在app.js中将所设置的文件夹设置成静态文件夹