【问题标题】:Allow just a type of file to be uploaded using React.js只允许使用 React.js 上传一种类型的文件
【发布时间】:2021-04-10 03:38:10
【问题描述】:

我在我的应用程序中使用了来自 Ant Design 的上传器。

function beforeUpload(file) {
  const filesFormats = [".doc", ".docx", "application/pdf"];
  console.log(file);
  const isRightFormat = filesFormats.includes(file.type);
  console.log(isRightFormat);
  if (!isRightFormat) {
    message.error("You can only upload pdf and doc files");
    return;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isRightFormat && isLt2M;
}

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

  handleChange = (info) => {
    console.log("info, ", info);
    if (info.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === "done") {
      // Get this url from response in real world.
      this.setState({ loading: false });
    }
  };

  render() {
    const { loading } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={true}
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        beforeUpload={beforeUpload}
        onChange={this.handleChange}
      >
        {uploadButton}
      </Upload>
    );
  }
}

我想要做的是限制某些可以上传的文件格式。比如我的限制不能上传图片:

const filesFormats = [".doc", ".docx", "application/pdf"];
console.log(file);
const isRightFormat = filesFormats.includes(file.type);
console.log(isRightFormat);
if (!isRightFormat) {
  message.error("You can only upload pdf and doc files");
  return;
}

代码有效,但是当我上传图片时,它仍然作为列表项出现在上传器图标中,但这应该是不可能的,因为我设置了限制。

为什么会发生以及如何实现我上面描述的?

Codesandbox link

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    您需要为您的Upload 组件使用accept 属性。格式指定here

    例如,

    <Upload accept='.doc,.docx,application/pdf'>
      Text
    </Upload>
    

    另请参阅文档以获取更多信息:https://3x.ant.design/components/upload/

    【讨论】:

    • 不错的答案,还有一个问题。如果你能提供帮助,那就太好了。我忘了添加问题,但是,您知道下一个问题的解决方案吗:例如,现在,如果您上传图像并将鼠标悬停在图标上,则会出现一个带有删除选项和预览选项的图标。如何预览我要上传的这些文件?例如pdf。谢谢
    • 使用onPreview 属性,然后您可以像这样嵌入PDF:stackoverflow.com/questions/14690000/how-to-embed-a-pdf
    • 即使我添加了 onPreview ,pdf 的预览也会被禁用。你能告诉我怎么做吗?它仅适用于图像。谢谢
    • 我对这个库不太熟悉。尝试在 GitHub 上询问维护人员或在此处提出新问题。
    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 2021-01-26
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多