element-plus中el-upload组件限制上传文件类型的方法
作者:幼稚鬼_Blog
Element Plus 中,el-upload 组件可以通过设置 accept 属性来限制上传文件的格式,这篇文章主要介绍了element-plus中el-upload组件限制上传文件类型,需要的朋友可以参考下
element-plus中el-upload组件限制上传文件类型
Element Plus 中,el-upload 组件可以通过设置 accept 属性来限制上传文件的格式
1.限制上传图片文件
<el-upload accept="image/*" action="/upload" :on-success="handleSuccess" > <el-button slot="trigger" size="small" type="primary">点击上传</el-button> </el-upload>
2.限制上传 Excel 文件
<el-upload accept=".xls,.xlsx" action="/upload" :on-success="handleSuccess" > <el-button slot="trigger" size="small" type="primary">点击上传</el-button> </el-upload>
Element-plus upload上传限制文件类型,文件大小
html部分:
<template> <el-upload v-model:file-list="fileList" class="upload-demo" :http-request="uploadFile" multiple :on-preview="handlePreview" :on-remove="handleRemove" :on-success="message" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" > <el-button type="primary">选择文件</el-button> <template #tip> <div class="el-upload__tip"> 支持格式:zip,ppt,pdf,word,excel,csv,png,jpg,单个文件不能超过20MB </div> </template> </el-upload> </template>
JS部分:
// 上传文件 const uploadFile = async (file) => { const allowedFileTypes = [ "application/vnd.ms-excel", // Microsoft Excel 表格 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //xlx "application/zip", // Zip files "application/vnd.ms-powerpoint", // PowerPoint files "application/pdf", // PDF files "application/msword", // Word files "application/vnd.openxmlformats-officedocument.wordprocessingml.document", //docx "text/csv", // CSV files "image/png", // PNG images "image/jpeg", // JPG images ]; const maxSize = 20 * 1024 * 1024; // 20MB if (file) { const options = { meta: { temp: "demo" }, mime: "json", headers: { "Content-Type": "text/plain" }, }; const isLt20M = file.file.size <= maxSize; if (!isLt20M) { ElMessage({ type: "error", message: "文件大小超过20MB", }); fileList.value = []; return false; // 阻止文件上传 } if (!allowedFileTypes.includes(file.file.type)) { ElMessage({ type: "error", message: "文件格式错误", }); fileList.value = []; return false; // 阻止文件上传 } try { //向后端上传文件 const result = await client.value.put(file.file.name, file.file, options); oosurl.value = result.url; } catch (e) { // Handle the error } } else { ElMessage.warning({ message: "No file selected", type: "warning", }); }
到此这篇关于element-plus中el-upload组件限制上传文件类型的文章就介绍到这了,更多相关element-plus限制上传文件类型内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!