文件上传校验文件是否更改(文件是否可读)

文件上传之后(文件信息暂存在前端,还未上传到后端),如修改原文件名,然后点击上传,会导致上传失败。所以在上传到后端之前需要校验文件。

校验方法:

export const checkFile = (file: any) => {
  return new Promise(resolve => {
    const reader: any = new FileReader();
    reader.readAsText(file, 'UTF-8');
    reader.onerror = () => {
      // read error caught here
      resolve({ success: false, msg: '文件发生变化请重新上传' });
    };
    reader.onload = () => {
      resolve({ success: true, msg: '' });
    };
  });
};

使用:

async uploadImportUser(option: any) {
      this.saveLoading = true;
      try {
        // 校验文件
        const checkFileResult: any = await checkFile(option.file);
        if (!checkFileResult.success) {
          this.$message.error(checkFileResult.msg);
          this.fileList = [];
          this.saveLoading = false;
          return;
        }
        const params = {
          templateFile: option.file,
          resourceTreeId: this.currentNode.id,
        };
        const { data, msg }: any = await apiSaveTreeBatchRelateImportUser(params);
        this.saveLoading = false;
        let confirmText: string = msg && msg !== 'Network Error' ? msg : '文件有误,请重新上传';
        if (data?.summaryMsg) {
          confirmText = `<div><b>${data.summaryMsg || ''}</b><br><br>`;
          if (data.errMsgList?.length) {
            confirmText += `<p>${data.errMsgList.join('<br>')}</p>`;
          }
          confirmText += '</div>';
        }
        this.$confirm(confirmText, '提示', {
          confirmButtonText: '确认',
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          dangerouslyUseHTMLString: true,
          customClass: 'upload-import-user-result-confirm',
        })
          .then(() => {})
          .catch(() => {})
          .finally(() => {
            this.close(false);
          });
      } catch (error) {
        console.log('上传导入失败:', error);
        this.showAlert('导入失败!');
        this.saveLoading = false;
        this.close(true);
      }
    }

码字不易,觉得有帮助的小伙伴点个赞支持下~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
您可以使用Ant Design Vue的Upload组件结合表单校验来实现文件上传前的校验。具体步骤如下: 1. 在表单中使用Upload组件,并设置相关属性,如: ``` <template> <a-form :form="form"> <a-form-item label="上传文件" name="upload" :rules="[ { required: true, message: '请上传文件' }, { validator: validateUpload } ]" > <a-upload :before-upload="beforeUpload" :on-success="onUploadSuccess" :on-error="onUploadError" > <a-button> <a-icon type="upload" /> 选择文件 </a-button> </a-upload> </a-form-item> <a-form-item> <a-button type="primary" @click="submitForm">提交</a-button> </a-form-item> </a-form> </template> <script> import { FormModel, Upload, Button, Icon } from 'ant-design-vue'; export default { components: { 'a-form': FormModel, 'a-form-item': FormModel.Item, 'a-upload': Upload, 'a-button': Button, 'a-icon': Icon }, data() { return { form: this.$form.createForm(this), uploadUrl: 'https://www.example.com/upload', uploadFile: null }; }, methods: { beforeUpload(file) { // 在上传之前进行校验,例如检查文件大小、类型等 const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error('上传文件大小不能超过 2MB!'); } return isLt2M; }, onUploadSuccess(response) { // 上传成功后的处理 this.uploadFile = response.file; }, onUploadError(error) { // 上传失败时的处理 this.$message.error(`上传失败: ${error}`); }, validateUpload(rule, value, callback) { // 自定义校验规则,例如检查文件类型是否符合要求 if (this.uploadFile && this.uploadFile.type !== 'image/jpeg') { callback(new Error('上传文件类型不正确')); } else { callback(); } }, submitForm() { this.form.validateFields((err, values) => { if (!err) { // 校验通过,提交表单 console.log(values); } }); } } }; </script> ``` 2. 在beforeUpload方法中进行上传前的校验,例如检查文件大小、类型等。 3. 在onUploadSuccess方法中处理上传成功后的文件信息。 4. 在validateUpload方法中自定义校验规则,例如检查文件类型是否符合要求。 5. 在submitForm方法中调用form.validateFields方法进行表单校验,校验通过后提交表单。 注意:以上代码仅供参考,具体实现方式需要根据您的业务需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张兴华(MarsXH.Chang)

喜欢的可以请作者喝杯咖啡~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值