Express+Vue2+Element-ui上传图片操作
1、Express创建upload目录
2、app.js中
app.use('/upload',express.static('upload'))
3、安装multiparty模块
npm i multiparty
4、router/student.js 中
const express = require('express') let router = express.Router() const multiparty = require("multiparty") router.post("/upImg",(req,res)=>{ let form = new multiparty.Form() form.uploadDir = "upload" form.parse(req,(err,formData,imgData)=>{ res.send({ imgPath:`http://localhost:3000/${imgData.file[0].path}` }) }) }) module.exports = router
5、Vue组件中
<el-form-item label="头像"> <el-upload class="upload-demo" action="http://localhost:3000/student/upImg" //后台上传图片接口 :file-list="fileList" :on-success="handleAvatarSuccess" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> </el-form-item> data(){ return{ imageUrl: '', //添加完成需置空 fileList:[], //添加完成需置空 } } methods:{ handleAvatarSuccess(res, file) { this.imageUrl = res.imgPath //后端返回的图片路径 }, }
6、渲染图片
<el-table-column prop="src" label="头像"> <template slot-scope="scope"> <img :src="scope.row.src" alt="" style="width: 100px;border-radius: 50px;height: 100px"> </template> </el-table-column>