zoukankan      html  css  js  c++  java
  • antd实战:表单上传,文件列表的过滤与限制。

    用表单上传组件最痛苦的地方是:

    他的诸多行为与纯上传组件不一样,而表单的文档关于这一块基本上没有提,只能自己试。

    比如我想做一个上传前的拦截。

    beforeUpload: (file, fileList) => {
          const isJpgOrPng =
            file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
          if (!isJpgOrPng) {
            message.error('您只能上传JPG或PNG图片');
            return false;
          }
          const isLt2M = file.size / 1024 / 1024 < 10;
          if (!isLt2M) {
            message.error('您的图片大于10M,请重新上传');
            return false;
          }
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            this.setState({
              logoUrl: reader.result,
            });
          };
        },

    这个代码在一般的上传是有效的,但是表单上传就不行。

    因为,就算你 return false 了,这个文件还是会进文件列表!

    所以只能在包裹上传组件的表单组件上动脑子了。

    HTML:

    <FormItem>
                        {getFieldDecorator(`upload_logo`, {
                          initialValue: undefined,
                          valuePropName: 'fileList',
                          getValueFromEvent: this.normFile,
                        })(
                          <Upload {...this.uploadLogoProps}>
                            <div
                              className={styles.logoBtn}
                              style={{ cursor: 'pointer' }}
                            ><button>
                                  点击上传图片
                                  <div className={styles.pos}>
                                    <Icon type="plus" />
                                  </div>
                                </button></div>
                          </Upload>,
                        )}
                      </FormItem>

    JS:

    // 上传控件用方法 LOGO
      // 项目照片只需要 1 个
      normFile = e => {
        let limit = 1;
        if (Array.isArray(e)) {
          return e;
        }
        return (
          e &&
          e.fileList &&
          e.fileList
            .filter((item, index, arr) => {
              return !!item.status;
            })
            .filter((item, index, arr) => {
              return index > arr.length - (limit + 1);
            })
        );
      };

    通过 status 的判断把没有上传的文件过滤掉。

    另外这个代码还做了另外一件事:

    .filter((item, index, arr) => {
              return index > arr.length - (limit + 1);
            })

    通过这个方法,让文件数组里只有一个文件对象。

    再次上传时,旧的会被新的顶掉。

    以上。

  • 相关阅读:
    pycharm上传代码到github中
    requests的封装(user-agent,proxies)
    Flask
    CTBCMCLibUser类
    TB timer 的用法
    多个 additional include directories 的复制方法
    怎样在编译时不显示警告
    infragistics 循环每一个选中的行
    Infragitics ultra grid 实现点击某一个cell的时候选中整行,并且不可编辑
    c#转换 datetime
  • 原文地址:https://www.cnblogs.com/foxcharon/p/12696732.html
Copyright © 2011-2022 走看看