element-plus的文件上传组件el-upload

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

要控制上传文件类型,可以使用el-upload的file-list属性,它是一个数组,用于存储已上传的文件列表。通过监听before-upload事件,可以在上传之前对文件进行检查和筛选。 示例代码: ```html <template> <el-upload class="upload-demo" action="/upload" :file-list="fileList" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadFiles">上传到服务器</el-button> </el-upload> </template> <script> export default { data() { return { fileList: [] }; }, methods: { beforeUpload(file) { // 判断文件类型是否符合要求 const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJpgOrPng) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); return false; } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); return false; } // 添加到fileList中 this.fileList.push(file); return false; }, onSuccess() { this.$message.success('上传成功'); }, onError() { this.$message.error('上传失败'); }, uploadFiles() { // 执行上传操作 this.$refs.upload.submit(); } } }; </script> ``` 在before-upload事件中,我们检查了文件类型和大小,如果符合要求,则将文件添加到fileList中。在上传之前,我们可以通过遍历fileList来控制上传的文件类型。 另外,我们将auto-upload属性设置为false,这样选择文件后不会自动上传,而是需要手动调用submit方法上传文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值