前端界面
upload
使用elment-ui的upload组件,action是上传图片的网址,上传成功后执行afterUpload方法
<el-upload
class="avatar-uploader"
:action="imgAction"
:show-file-list="false"
:on-success="afterUpload">
<img v-if="model.icon" :src="model.icon" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
computed: {
imgAction () {
rerurn this.$http.defaults.baseURL + '/upload'
}
},
methods: {
afterUpload (res) {
// res 是 element 的on-success附带参数
// 数据赋值会有问题,需要显式赋值
// this.model.icon = res.url; // 获取后台生成的url,赋值给model.icon
this.$set(this.model, 'icon', res.url); // vue推荐用法
}
}
显示
el-table-column里的template
<el-table-column prop="icon" label="图标">
<template slot-scope="scope">
<img :src="scope.row.icon" alt="图标" style="height:3rem">
</template>
</el-table-column>
node端
multer
在路由文件中导入multer,并建立中间件
const multer = require('multer');
// 这里使用绝对地址
const upload = multer({ dest: __dirname + '/../../uploads' });
将中间件加入路由,single代表单次上传,file传入子路由
app.post('admin/api/upload', upload.single('file'), async (req, res) => {
const file = req.file;
file.url = `http://localhost:3000/uploads/${file.filename}`;
res.send(file);
});
静态文件托管
在入口文件中设置托管
app.use('/uploads', express.static(__dirname + '/uploads'));