前端
这里我们利用elementui实现文件上传,利用accept限制上传文件类型,同时通过js限制上传大小,借口返回后调用uploadSuccess得到url。
<el-upload
class="upload-demo"
action="/api/album/upload"
:on-success="uploadSuccess"
:before-upload="uploadBefore"
accept="image/*"
>
<el-button size="mini" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传图片,且不超过5000kb</div>
</el-upload>
uploadSuccess(res) {
this.uploadDataForm.url = res.data.path;
},
uploadBefore(file) {
let limitMax = 5000 * 1024;
if (file.size > limitMax) {
this.$messageTips("大小超出限制");
return false;
}
},
后端
利用multer上传文件,然后重新给文件命名,一般可以通过时间戳和用户使命名不重复。
var multer = require('multer')
var router = express.Router();
router.post('/upload', multer({
//设置文件存储路径
dest: 'public/img'
}).array('file', 1), function (req, res, next) {
let files = req.files;
let file = files[0];
let fileInfo = {};
let path = 'public/img/' + Date.now().toString() + '_' + file.originalname;
fs.renameSync('./public/img/' + file.filename, path);
//获取文件基本信息
fileInfo.type = file.mimetype;
fileInfo.name = file.originalname;
fileInfo.size = file.size;
fileInfo.path = path;
res.json({
code: 0,
msg: 'OK',
data: fileInfo
})
});