Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a file in antd Upload component

I have this Upload component that I got from antd : react ant design documentation

<Upload
  beforeUpload={()=> {
    return false; }}
  onChange={e => onChangeFile(e, index)}
  onRemove={e => onRemoveFile(e, index)}
>
  <Button
    icon={<UploadOutlined />}
  >
    Upload a file
  </Button>
</Upload>

After uploading the file, a remove icon appears. When I click on the remove button the file does not get removed from the state.

here is the onChange function :

const onChangeFile = (info, index) => {
    console.log("onChange info = " + info);
    const newForm = form;
    newForm.inputs[index].value = info.file;
    setForm({
      ...form,
      from: newForm
    });
    console.log("onChange form = " + form);
};

I tried removing it using onRemove function like this:

const onRemoveFile = (info, index) => {
   console.log("onRemove info = " + info);
   const newForm = form;
   newForm.inputs[index].value = null;
   setForm({
     ...form,
     from: newForm
   });
   console.log("onRemove form = " + form);
};

the output of the console logs :

enter image description here

screenshot of the UI:

enter image description here

feel free to try a few things in this code example provided by antd:

https://codesandbox.io/s/qj6n3?file=/index.js

like image 314
Ala Ben Aicha Avatar asked Sep 11 '25 21:09

Ala Ben Aicha


1 Answers

You can achieve that by following this example:

const normFile = (e) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e && e.fileList;
};

<Form onFinish={() => {}}>
    <Form.Item
        name="tagList"
        label="Upload"
        valuePropName="list"
        getValueFromEvent={normFile}
        rules={[
            {
                required: true,
                message: 'Tag list is required',
            },
        ]}
    >
        <Upload
            beforeUpload={() => false}
            listType="picture-card"
        >
            <UploadOutlined style={{ marginRight: 5 }} />
            Upload
        </Upload>
    </Form.Item>
</Form>

like image 131
Zain Khan Avatar answered Sep 14 '25 12:09

Zain Khan