【问题标题】:React Ant design file upload only xls file validationReact Ant 设计文件仅上传 xls 文件验证
【发布时间】:2020-07-28 03:25:40
【问题描述】:

我正在为 ant design file upload 使用我的反应项目,我在上传时遇到了一些冲突,我尝试仅验证上传 .xls 文件,但它不起作用。我将 png 更改为 xls 但无法正常工作有人知道如何正确操作吗?

stack blitz here

代码在这里

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class Avatar extends React.Component {
  state = {
    loading: false,
  };

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }
  };

  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const { imageUrl } = this.state;
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        beforeUpload={beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

谢谢

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    您必须根据 MIME types docs 调整所需文件格式 (file.type) 的 mimeType。

    对于.xls,您可以找到正确的类型:

    .xls Microsoft Excel 应用程序/vnd.ms-excel

    这将导致以下检查:

    const isXls = file.type === 'application/vnd.ms-excel';
    

    此外,您可以向Upload 对话框添加过滤器,以仅显示您想要的类型的文件(请参阅Antd's Upload Api doc)。

    accept 可以接受的文件类型。见输入接受属性

    <Upload
            accept="application/vnd.ms-excel"
    ...
    />
    

    这是一个有效的Demo Stackblitz

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多