本页导航
article
uploadLocal使用
AI摘要
本文介绍了uploadLocal文件上传组件的功能和使用方法。该组件支持导入文件处理函数,允许设置文件类型和大小限制,并且通过插槽机制支持自定义上传按钮和界面。文中提供了多种示例,包括基础用法、带参数配置和自定义按钮,以及如何用uploadLocal实现类似uploadCos的拖拽上传UI。整体来看,uploadLocal组件灵活且易用,适合多样化的文件上传需求。
说明
按钮式文件上传组件
参数
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| importFile | Function | 是 | - | 导入文件处理函数,接收文件对象作为参数 |
| allowedExtensions | Array | 否 | [] | 允许的文件扩展名,如 [’.xlsx’, ‘.xls’, ‘.csv’] |
| maxFileSize | Number | 否 | 10 | 单个文件上传大小限制(单位:MB) |
| acceptType | String | 否 | “*” | 允许上传的文件类型 |
插槽
| 插槽名 | 说明 |
|---|---|
| default | 默认插槽,用于自定义上传按钮文本 |
| trigger | 触发按钮插槽,可完全自定义上传按钮 |
使用示例
基本使用
<uploadLocal :importFile="handleImportFile">
导入Excel
</uploadLocal>
带参数使用
<uploadLocal
:importFile="handleImportFile"
:allowedExtensions="['.xlsx', '.xls', '.csv']"
:maxFileSize="20"
acceptType=".xlsx,.xls,.csv"
>
导入
</uploadLocal>
使用插槽自定义内容
<template>
<div>
<uploadLocal :importFile="handleImportFile">
<!-- 自定义按钮文本 -->
点击导入数据文件
</uploadLocal>
<!-- 完全自定义按钮 -->
<uploadLocal :importFile="handleImportFile">
<template #trigger>
<el-button type="success" icon="el-icon-upload">
导入数据
</el-button>
</template>
</uploadLocal>
</div>
</template>
<script setup>
// 处理导入Excel文件
const handleImportFile = (file) => {
console.log('处理导入的文件:', file.name)
// 实际项目中在这里处理Excel文件
console.log('文件大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
console.log('文件类型:', file.type)
}
</script>
使用uploadLocal实现uploadCos的UI
可以通过利用uploadLocal组件的插槽功能,实现与uploadCos相似的UI效果:
<template>
<div>
<uploadLocal :importFile="handleFileUpload">
<template #trigger>
<div class="el-upload-dragger">
<el-icon class="el-upload-icon" size="100">
<upload-filled />
</el-icon>
<div class="el-upload__text">拖拽或 <em>点击上传</em></div>
<img v-if="imageUrl" :src="imageUrl" alt="img" class="preview-img" />
</div>
</template>
</uploadLocal>
</div>
</template>
<script setup>
import { UploadFilled } from "@element-plus/icons-vue";
import { ref } from 'vue';
const imageUrl = ref('');
// 处理文件上传的函数
const handleFileUpload = async (file) => {
// 调用你的上传API
try {
const response = await yourUploadFunction(file);
imageUrl.value = response.data; // 根据你的API响应结构调整
} catch (error) {
console.error('上传失败', error);
}
}
</script>
<style>
.preview-img {
width: 100%;
height: 100%;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
</style>
最后更新于 2025-09-30 20:31