使用el-upload上传文件时,文件二选一,点击保存按钮时再上传

项目中要求上传的文件二选一即可,上传的同时携带其他参数

  1. 设置auto-upload为"false"取消自动上传
  2. 在data属性里携带其他参数,action是上传文件用到的接口
  3. 文件二选一,我使用的方法是放一个假的上传文件按钮。当选择了文件A的时候,B文件的上传按钮移除,提供一个假的按钮,状态为禁用
  4. 获取el-upload的实例对象,点击保存按钮时,调用Element UI提供的submit方法,就可以在点击保存的时候上传文件
    代码如下
<el-form ref="ruleFormRef" class="plain-wrap" :model="form" :rules="rules">
  <el-form-item label="方案名称" prop="file_name">
    <el-input
      placeholder="填写方案名称"
      v-model="form.file_name"
    ></el-input>
  </el-form-item>
  <el-form-item label="方案计算" prop="data">
    <div class="plain-wrap__item">
      <div class="plain-wrap__alert">
        (文件上传二选一,提供计算文件或完整出率文件)
      </div>
      <div class="plain-wrap__upload">
        <div class="plain-wrap__upload__template">
          <span class="label">① 计算文件</span>
          <el-button
            type="primary"
            link
            size="small"
            @click="handleGetTemplate"
            >模板</el-button
          >
        </div>
        <el-upload
          v-if="isComputed"
          ref="computedUploadRef"
          name="data"
          :data="{
            file_name: form.file_name,
            data_id: RateFileType.COMPUTED
          }"
          :limit="1"
          :auto-upload="false"
          :headers="{ token: storage.get(StorageEnum.ACCESS_TOKEN) }"
          :on-exceed="handleExceed"
          :on-change="handleComputedChange"
          :on-remove="handleRemoveFile"
          :on-success="handleSuccess"
          :on-error="handleErroe"
          :before-upload="handleBeforeUpload"
          :action="`${baseUrl}/xxx`"
        >
          <el-button type="primary">上传文件</el-button>
        </el-upload>
        <el-button v-else type="primary" :disabled="!isComputed"
          >上传文件</el-button
        >
      </div>

      <div class="plain-wrap__upload">
        <div class="plain-wrap__upload__template">
          <span class="label">② 出率文件</span>
          <el-button
            type="primary"
            link
            size="small"
            @click="handleGetTemplate"
            >模板</el-button
          >
        </div>
        <el-upload
          v-if="isRate"
          ref="rateUploadRef"
          name="data"
          :data="{
            file_name: form.file_name,
            data_id: RateFileType.RATE
          }"
          :limit="1"
          :auto-upload="false"
          :headers="{ token: storage.get(StorageEnum.ACCESS_TOKEN) }"
          :on-exceed="handleExceed"
          :on-change="handleRateChange"
          :on-remove="handleRemoveFile"
          :on-success="handleSuccess"
          :on-error="handleErroe"
          :before-upload="handleBeforeUpload"
          :action="`${baseUrl}/xxx`"
        >
          <el-button type="primary" :disabled="!isRate">上传文件</el-button>
        </el-upload>
        <el-button v-else type="primary" :disabled="!isRate"
          >上传文件</el-button
        >
      </div>
    </div>
  </el-form-item>
</el-form>

<div>
  <el-button @click="handleCancel">取消</el-button>
  <el-button type="primary" @click="handleSave">保存</el-button>
</div>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { storage } from "@/utils/storage";
import { StorageEnum } from "@/enums/storage";
import { UploadRawFile, UploadFile, ElMessageBox } from "element-plus";
import { RateFileType } from "@/enums/card-pool";

const router = useRouter();
const baseUrl = import.meta.env.VITE_REQUEST_URL;

const form = reactive<AnyObject>({});

const rules = reactive<FormRules>({
  file_name: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
  data: [{ required: true, message: "请上传相应文件", trigger: "change" }]
});

const isComputed = ref(true);
const isRate = ref(true);

const handleExceed = () => {
  ElMessage.error("文件数量超出限制");
};

const handleSuccess = () => {
  ElMessage.success("添加成功");
  router.push("/xxx");
};

// 上传计算文件时,移除出率文件的上传按钮
const handleComputedChange = (file: UploadFile) => {
  form.data = file.raw;
  isRate.value = false;
};

// 上传出率文件时,移除计算文件的上传按钮
const handleRateChange = (file: UploadFile) => {
  form.data = file.raw;
  isComputed.value = false;
};

// 移除文件时,将两个按钮的状态初始化
const handleRemoveFile = () => {
  isComputed.value = true;
  isRate.value = true;
  form.data = null;
};

const handleErroe = (error: Error) => {
  const err = JSON.parse(error.message);
  ElMessage.error(err.msg || "添加失败");
};

const handleBeforeUpload = async (file: UploadRawFile) => {
  let acceptList = ["xlsx", "xls"];
  let fileType = (file.name.split(".").pop() || "").toLowerCase();
  if (acceptList.indexOf(fileType) === -1) {
    ElMessage.error("仅支持xlsx、xls文件");
    return false;
  }
};

const handleGetTemplate = () => {
  ElMessageBox.alert(
    "【金山文档】 xx相关文件模板https://xxxxxxxxxxxxx"
  );
};

const handleCancel = () => {
  router.back();
};

const ruleFormRef = ref<FormInstance>();
const computedUploadRef = ref();
const rateUploadRef = ref();
const handleSave = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      isComputed.value
        ? computedUploadRef.value.submit()
        : rateUploadRef.value.submit();
    }
  });
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现el-upload上传文件点击预览的功能,可以通过以下步骤实现: 1. 在el-upload组件中添加一个自定义的slot,用于显示预览按钮。 2. 在handleFileChange函数中,将上传文件保存到一个数组中,同为每个文件生成一个唯一的id。 3. 在预览按钮点击事件中,根据文件的id获取对应的文件内容,并将其显示在一个弹窗中。 4. 在弹窗中添加一个删除按钮,用于删除当前预览的文件。 代码示例: ``` <el-upload class="upload-demo" ref="uploadFile" :auto-upload="false" :action="testForm.actionUrl" drag :file-list="testForm.fileList" :on-change="handleFileChange" :on-remove="removeFile" :limit="1" :on-exceed="overLimitCount" > <el-button slot="trigger" size="small" type="primary">选择文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> <el-button slot="preview" size="small" type="text" @click="showPreview">预览</el-button> </el-upload> data() { return { testForm: { fileList: [], fileContentList: [] }, previewFileId: '', isShowPreview: false } }, methods: { handleFileChange(files, fileList) { this.testForm.fileList = fileList files.forEach(file => { const reader = new FileReader() reader.readAsText(file.raw) reader.onload = e => { const fileContent = e.target.result.replace(/\n|\r\n/g, '<br/>') this.testForm.fileContentList.push({ id: file.uid, content: fileContent }) } }) }, showPreview() { if (this.testForm.fileContentList.length > 0) { this.previewFileId = this.testForm.fileContentList[0].id this.isShowPreview = true } }, removeFile(file, fileList) { const index = this.testForm.fileContentList.findIndex(item => item.id === file.uid) if (index !== -1) { this.testForm.fileContentList.splice(index, 1) } }, removePreview() { const index = this.testForm.fileContentList.findIndex(item => item.id === this.previewFileId) if (index !== -1) { this.testForm.fileContentList.splice(index, 1) this.isShowPreview = false } } }, computed: { previewFileContent() { const file = this.testForm.fileContentList.find(item => item.id === this.previewFileId) return file ? file.content : '' } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值