一、先在后端安装multiparty包
npm i multiparty
二、在后端项目中创建一个upload文件
三、在后端项目app.js中配置图片上传的路径
四、在routers文件下index.js中编写上传接口
//引入multiparty包
var multiparty = require('multiparty')
//上传图片
router.post('/uploadImg',(req,res)=>{
let form = new multiparty.Form()
form.uploadDir = 'upload'
form.parse(req,(err,a,imgData)=>{
res.send({
code:200,
path:'http://localhost:3000/' + imgData.file[0].path
})
})
})
五、前端图片展示列表
<el-table-column prop="path" label="图片">
<template slot-scope="scope">
<el-image
style="width: 100px; height: 100px"
:src="scope.row.path"
:preview-src-list="[scope.row.path]">
</el-image>
</template>
</el-table-column>
六、前端form表单中点击按钮获取图片进行添加到数据库
<el-form-item label="图片" :label-width="formLabelWidth">
<el-upload
class="avatar-uploader"
action="http://localhost:3000/uploadImg"
:show-file-list="false"
:on-success="success"
:before-upload="beforeAvatarUpload">
<img v-if="form.path" :src="form.path" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
methods: {
success(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.form.path = res.path
},
beforeAvatarUpload(file) {
const isGIF = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isGIF) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isGIF && isLt2M;
}
}