【Ant Design of Vue】Excel和txt文件的上传与校验

一、需求

  • 实现 .xls.txt 文件的上传功能,并添加表单必传校验

二、技术栈

  • 前端框架:vue2
  • 前端UI框架:Ant Design of Vue(v1.7.8)

三、代码

上传 .xls 文件

<template>
  <a-modal
    :title="title"
    ok-text="确认"
    cancel-text="取消"
    :visible="visible"
    :maskClosable="false"
    destroyOnClose
    @ok="save"
    @cancel="reset"
  >
    <a-form-model :model="form" ref="ruleForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item ref="name" label="Activity name" prop="name">
        <a-input v-model="form.name" />
      </a-form-model-item>
      <a-form-model-item label="文件" prop="file">
        <a-upload
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        >
          <a-button> <a-icon type="upload" /> 选择文件 </a-button>
          <a-badge color="red" text="请选择.xls文件" style="margin-left: 10px" />
        </a-upload>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
export default {
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      visible: false,
      title: '文件导入',
      form: {},
      // 校验规则
      rules: {
        file: [
          {
            required: true,
            trigger: 'change',
            validator: this.uploadFileChange,
          },
        ],
      },
      // 已经上传的文件列表
      fileList: [],
    };
  },
  methods: {
    // 上传文件改变时的状态
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败`);
      }
    },
    // 关闭
    reset() {
      this.fileList = [];
      this.visible = false;
    },
    // 确认
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const { fileList } = this;
          const formData = new FormData();
          fileList.forEach((file) => {
            formData.append('file', file);
          });
          // 上传文件接口请求,一般将文件内容放在body里面
          // api.xxx(formData).then((res) => {});
          this.reset();
        } else {
          return false;
        }
      });
    },
    // 自定义上传附件校验
    uploadFileChange(rule, value, callback) {
      if (this.fileList.length === 0) {
        return callback(new Error('请选择需要上传的文件'));
      } else {
        return true;
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      return false;
    },
  },
};
</script>

<style lang='less' scoped>
/deep/ .ant-badge-status-text {
  color: red;
}
</style>

备注:上传 txt 文件时将 <a-upload>accept 修改为 text/plain 即可

四、效果

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3.0中使用ant-design-vue上传文件,需要先安装ant-design-vue和axios模块: ```bash npm install ant-design-vue axios --save ``` 然后在需要使用上传组件的页面中,引入ant-design-vue和axios模块: ```javascript import { Upload, Button } from 'ant-design-vue'; import axios from 'axios'; ``` 然后在页面中,添加上传组件: ```html <template> <div> <upload :action="uploadUrl" :headers="headers" :showUploadList="false" :beforeUpload="beforeUpload" :onSuccess="onSuccess" :onError="onError" > <button> <a-button> <a-icon type="upload" /> Click to Upload </a-button> </button> </upload> </div> </template> ``` 其中,`uploadUrl`是上传文件的接口地址,`headers`是上传文件时需要携带的请求头,`beforeUpload`是上传文件前的校验函数,`onSuccess`和`onError`分别是上传成功和上传失败的回调函数。 在页面的`script`中,需要定义这些属性的值以及`beforeUpload`、`onSuccess`、`onError`函数的实现: ```javascript export default { name: 'UploadPage', components: { Upload, Button }, data() { return { uploadUrl: '/api/upload', headers: { Authorization: 'Bearer ' + localStorage.getItem('token') } }; }, methods: { beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { this.$message.error('You can only upload JPG/PNG file!'); return false; } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error('Image must smaller than 2MB!'); return false; } return true; }, onSuccess(response, file) { this.$message.success('Upload successfully!'); }, onError(error, response, file) { this.$message.error('Upload error!'); } } }; ``` 其中,`beforeUpload`函数用来进行文件类型和大小的校验,`onSuccess`和`onError`函数用来处理上传成功和上传失败的情况。 最后,在页面的`style`中,可以添加一些样式来美化上传按钮: ```css button { margin-top: 16px; } button .ant-btn { width: 100%; } button .anticon-upload { margin-right: 8px; } ``` 这样,就可以在Vue3.0中使用ant-design-vue上传文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值