el-upload组件 支持多种风格,如文件列表,图片,图片卡片,支持多种事件,预览,删除,上传成功,上传中等钩子。
file-list:上传的文件集合,一定要用v-model:file-list进行双向绑定。
list-type:决定文件类型,filelist,picture,picture-card 3种
用法示例
vue代码
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance,FormRules,UploadUserFile } from 'element-plus'
interface Good {
}
const goodForm=ref<Good>({
});
const fileList=ref<UploadUserFile[]>()
const picFileList=ref<UploadUserFile[]>()
const picCardFileList=ref<UploadUserFile[]>()
const previewDialogVisable=ref(false)
const previewPicUrl=ref()
const previewFunc = (uploadFile:UploadUserFile)=>{
previewDialogVisable.value=true
previewPicUrl.value=uploadFile.url
}
</script>
<template>
<el-form :model="goodForm" status-icon label-position="left" label-width="auto" ref="formRef">
<el-form-item label="select file">
<el-upload v-model:file-list="fileList" action="http://localhost:3000/upload">
<template #trigger>
<el-button type="primary">select file</el-button>
</template>
</el-upload>
</el-form-item>
<el-form-item label="select pic file">
<el-upload v-model:file-list="picFileList" list-type="picture" action="http://localhost:3000/upload">
<template #trigger>
<el-button type="primary">select file</el-button>
</template>
</el-upload>
</el-form-item>
<el-form-item label="picture card file">
<el-upload v-model:file-list="picCardFileList" action="http://localhost:3000/upload" list-type="picture-card" :on-preview="previewFunc">
<template #trigger>
<el-button type="primary">select file</el-button>
</template>
</el-upload>
</el-form-item>
<el-dialog v-model="previewDialogVisable" >
<img :src="previewPicUrl" alt="preview image" w-full/>
</el-dialog>
</el-form>
</template>
<style scoped>
</style>
后端用node+ts
import express from 'express';
import multer from 'multer';
import path from 'path';
import cors from 'cors';
// 初始化 express 应用
const app = express();
app.use(cors())
// 设置文件存储配置
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // 文件存储目录
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)); // 文件名
}
});
const upload = multer({ storage: storage });
// 创建文件上传路由
app.post('/upload', upload.single('file'), (req, res) => {
res.send({
message: 'File uploaded successfully',
file: req.file
});
});
app.use(express.static(path.join(__dirname, '../uploads')));
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
demo 地址
https://github.com/haozhi-ly/elment-plus-demo
https://element-plus.org/zh-CN/component/upload.html#%E5%B1%9E%E6%80%A7