Asking
Asking

Reputation: 4192

Allow just a type of file to be uploaded using React.js

I am using in my application an uploader from 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>
    );
  }
}

What I am trying to do is to restrict some formats of files that can be uploaded. For example, images should't be uploaded according to my restriction:

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;
}

The code works but when I upload an image, it still appears in the uploader icon as a list item, but it should't be possible, because I set the restriction.

Why does it happen and how to achieve what I described above?

Codesandbox link

Upvotes: 0

Views: 12135

Answers (1)

Abhyudaya Sharma
Abhyudaya Sharma

Reputation: 1292

You need to use the accept property for your Upload component. The format is specified here.

For example,

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

Also look at the docs for more information: https://3x.ant.design/components/upload/

Upvotes: 7

Related Questions