前端界面
upload
使用elment-ui的upload組件,action是上傳圖片的網(wǎng)址,上傳成功后執(zhí)行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附帶參數(shù)
// 數(shù)據(jù)賦值會有問題笼痛,需要顯式賦值
// 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="圖標(biāo)">
<template slot-scope="scope">
<img :src="scope.row.icon" alt="圖標(biāo)" style="height:3rem">
</template>
</el-table-column>
node端
multer
在路由文件中導(dǎo)入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);
});
靜態(tài)文件托管
在入口文件中設(shè)置托管
app.use('/uploads', express.static(__dirname + '/uploads'));
效果
image.png
image.png