Vue3+ElementPlus+koa2实现本地图片的上传
以下是一个使用Vue 3、Element Plus和Koa 2实现的本地图片上传的简单示例。
Vue 3 前端代码(Upload.vue
):
<template>
<el-upload
action="http://localhost:3000/upload"
:on-success="handleSuccess"
:on-error="handleError"
>
<el-button slot="trigger" size="small" type="primary">选择图片</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
</el-upload>
</template>
<script setup>
import { ElMessageBox } from 'element-plus'
const handleSuccess = (response, file, fileList) => {
console.log('File uploaded successfully:', response)
ElMessageBox.alert('图片上传成功', '提示')
}
const handleError = (err, file, fileList) => {
console.error('Error during upload:', err)
ElMessageBox.alert('图片上传失败', '提示')
}
</script>
Koa 2 后端代码(server.js
):
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const app = new Koa();
const router = new Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/') // 确保这个文件夹已经存在
},
filename: function (req, file, cb) {
let ext = file.originalname.substring(file.originalname.lastIndexOf('.'));
cb(null, file.fieldname + '-' + Date.now() + ext)
}
})
const upload = multer({ storage: storage })
router.post('/upload', upload.single('file'), async (ctx) => {
ctx.body = {
code: 200,
message: '文件上传成功',
data: {
name: ctx.file.originalname,
path: ctx.file.path,
size: ctx.file.size
}
}
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
确保你已经安装了必要的依赖:
npm install element-plus vue@next @vue/compiler-sfc koa koa-multer multer
运行服务器:
node server.js
然后运行 Vue 应用。上传功能现在应该可以在 http://localhost:3000
上通过 Element Plus 的上传组件使用了。
评论已关闭