使用Element的upload组件和nodejs实现图片上传
html和css
/*html*/
<el-form-item label="用户头像" prop="imgUrl">
<el-upload
class="avatar-uploader"
action="http://127.0.0.1:8888/upload"
:show-file-list="false"
:on-success="uploadSuccess"
:before-upload="uploadBefore"
accept="image/*"
>
<img v-if="imgUrl" :src="imgUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
/*css*/
<style lang="scss" scoped>
.avatar-uploader {
width: 178px;
height: 178px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
js部分
//图片上传成功
uploadSuccess(res, file) {
this.imgUrl = URL.createObjectURL(file.raw);
},
//图片上传之前
uploadBefore(file) {
let limitMax = 5000 * 1024;
if (file.size > limitMax) {
this.$messageTips("大小超出限制");
return false;
}
}
nodejs部分
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const app = new express();
//图片上传
app.post(
"/upload",
multer({
//设置文件存储路径
dest: "public/image",
}).array("file", 1),
function (req, res, next) {
let files = req.files;
let file = files[0];
let fileInfo = {};
let path = "public/image/" + Date.now().toString() + "_" + file.originalname;
fs.renameSync("./public/image/" + file.filename, path);
//获取文件基本信息
fileInfo.type = file.mimetype;
fileInfo.name = file.originalname;
fileInfo.size = file.size;
fileInfo.path = path;
res.json({
code: 200,
msg: "OK",
data: fileInfo,
});
}
);
参考文章: https://blog.csdn.net/qq_43138078/article/details/90265823.