react-文件上传

利用antd的Upload组件

onFilebeforeUpload = (file) => {
    let fileContent = null;
    const isP12 = file.type === 'application/x-pkcs12';
    const { password } = this.state;
    if (!isP12) {
      message.error('您上传的不是.p12格式文件!');
    }
    const isLt40KB = file.size < 40960;
    if (!isLt40KB) {
      message.error('您上传的证书文件超过40K,请重新确认文件大小!');
    }
    const fr = new FileReader();
    fr.readAsDataURL(file);
    fr.onload = () => {
      fileContent = fr.result;
      if (isP12 && isLt40KB) {
        if (password) {
          this.setState({
            ...this.state,
            ...{
              btnCert: false,
              fileList: [file],
              fileContent,
            },
          });
        } else {
          this.setState({
            ...this.state,
            ...{
              fileList: [file],
              fileContent,
              btnCert: true,
              modelCert: {
                items: this.initItemsCert(false),
              },
            },
          });
        }
      } else {
        this.setState({
          ...this.state,
          ...{
            fileList: [],
            fileContent: {},
          },
        });
        this.fileContent = {};
      }
    };
    return isP12 && isLt40KB;
  };


render(){
return(

 <Upload
                  name="file"
                    accept="application/x-pkcs12"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    beforeUpload={this.onFilebeforeUpload}
                    onRemove={this.onFileRemove}
                    fileList={fileList}
                  >
                    <Button>
                      <Icon type="upload" /> 选择文件
                    </Button>
                  </Upload>
)

}

如果是正常的input的话

 onGetFile = (e) => {
    const file = e.target.files[0];
    const fr = new FileReader();
    fr.readAsDataURL(file);
    let fileContent = null;
    fr.onload = () => {
      fileContent = fr.result;
    };
    setTimeout(() => {
      console.log('fileContent', fileContent);
    }, 100);
  };


        <input type="file" onChange={this.onGetFile} />
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,734评论 0 38
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 7,591评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,312评论 19 139
  • 20/100 #100天坚持一件事# 周二 晴 简易早餐 《圣经》罗马书7-9章: 印象深刻的经文:神既不爱惜自己...
    zuimeideni阅读 1,183评论 0 0
  • 一直以来,我对自己的评价,就是一个“胆小鬼”。不管做什么事情,都是想得很多做的很少,总是不能跨出的关键的一步...
    白风掌门阅读 793评论 0 0