Vamsi
Vamsi

Reputation: 392

How to write conditions while uploading file in React

I am very New to React, I am trying to Upload files, after uploading files it has to upload only these formats Video,Photos,Pdf,Excel file,Docs,Csv,Audio and size should not exceeded more that 25 mb, can you please tell me how to resolve this issue. I am not aware what event I have to use while uploading file. This is what I tried.

import React from "react";
import 'antd/dist/antd.css';
import { Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import "./App.css";

const App = () => {
  return (
    <div>
      <Upload>
        <Button>
          <UploadOutlined />Click to Upload
        </Button>
      </Upload>
    </div>
  )
}

export default App
```

Upvotes: 1

Views: 565

Answers (1)

Shahed Mahmoudi
Shahed Mahmoudi

Reputation: 281

beforeUpload only prevent upload behavior when return false or reject promise, the prevented file would still show in file list. Here is the example you can keep prevented files out of list by return UPLOAD.LIST_IGNORE.

import React, { useState } from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

const Uploader = () => {
const props = {
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 < 25;
   if (!isLt2M) {
       message.error('Image must smaller than 25MB!');
   }
      return isJpgOrPng && isLt2M ? true : Upload.LIST_IGNORE;      
},
onChange: info => {
  console.log(info.fileList);
},
 };
return (
    <Upload {...props}>
       <Button icon={<UploadOutlined />}>Upload png only</Button>
    </Upload>
     );
   };

Upvotes: 2

Related Questions