javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > el-upload两种上传方式

el-upload两种不同的上传方式实现分析

作者:西瓜有点饿

el-upload提供了诸多处理,为我们日常开发提供了便利性,同时也存在着一些边界没有处理,这篇文章主要介绍了el-upload两种不同的上传方式实现的相关资料,需要的朋友可以参考下

第一种:选择文件 → 确认上传,两个步骤分离

<el-upload ref="uploadRef" :disabled="loading"
    :auto-upload="false"
    :on-change="handleFileChange"
    :file-list="fileList">

    <template #trigger>
        <el-button type="primary">选取文件</el-button>
    </template>

    <template #tip>
        <div class="text-xs text-red mt-2">文件格式为xls,xlsx文件,单次最多上传1000条</div>
    </template>
            
    <el-button :loading="loading" type="primary" @click="onUpload">确 定</el-button>
</el-upload>

const handleFileChange = (file: any, files: any[]) => {
    // 校验文件格式
    const ext = file.name.split('.').pop()?.toLowerCase()
    if (!['xls', 'xlsx'].includes(ext)) {
        message.error('请上传 xls/xlsx 格式的文件')
        // 移除不合法的文件
        uploadRef.value?.clearFiles()
        fileList.value = []
        return
    }
    // 合法文件,更新列表
    fileList.value = [file]
}

const onUpload = async () => {
    // 检查是否有文件
    if (fileList.value.length === 0) {
        message.warning('请先选择文件')
        return
    }

    try {
        loading.value = true
        const params = new FormData()
        params.append('file', fileList.value[0].raw)
        const res = await UploadAPPListConfig(params)        
        // 上传成功
        if(res.code === 0 && res.data) {
            message.success(res.data)
            dialogVisible.value = false
            emit('success')
        }
    } finally {
        loading.value = false
    }
}

核心配置:

第二种:选择后自动触发上传

<el-upload 
    :auto-upload="true"
    :show-file-list="false" 
    :disabled="updLoading"
    :before-upload="onBeforeUpload" 
    :http-request="onUpload" >
    <el-button type="primary" :loading="updLoading">选取文件</el-button>
</el-upload>

const onBeforeUpload = (file) => {
    // Excel 判断(推荐用扩展名)
    const ext = file.name.split('.').pop()?.toLowerCase()
    if (!['xls', 'xlsx'].includes(ext)) {
        message.error('请上传 xls/xlsx 格式的文件')
        return false
    }
    return true //允许上传
}

const onUpload = async (updFile) => {
    try {
        updLoading.value = true
        const file = updFile.file
        const params = new FormData()
        params.append('file', file)
        const res = await UploadTeleExcel(params)
        message.success('上传成功')
        // 全部成功才能上传
        formData.value.successPhones = res.data.failPhones.length === 0 && res.data.successPhones.length > 0 ? res.data.successPhones: []
    } finally {
        updLoading.value = false
    }
}

核心配置:

对比总结

维度第一种第二种
上传流程两步式(选择→确认)一步式(选择即上传)
文件列表显示并管理不显示
文件状态可缓存、可重置即用即传,无状态
用户控制用户主动触发上传系统自动触发
错误处理可重新选择文件需要重新选择
复杂度较高较低
适用场景表单提交、批量导入快速上传、单附件

到此这篇关于el-upload两种不同的上传方式实现分析的文章就介绍到这了,更多相关el-upload两种上传方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文