reactjsantd

How to upload a file and show it in a dialog window


I am using React with Ant Design as component library. I want to implement the following behavior:

The user clicks a button and the Explorer window opens to upload a file. When the user clicks to select a file, a popup window appears showing the file. My problem is that the uploaded file is displayed next to the button. I don't know how to prevent it from appearing there and instead show it in the popup window. I struggle to understand how to structure my components and how they should interact.

For example my component UploadFile: How do I trigger the upload window without being the button the respective upload area?

function UploadFile() {
  const onUpload = () => {
    console.log('asdf')
  }

  return (
    <Upload name="file" accept=".json" customRequest={onUpload}>
      <Button icon={<ImportIcon />} />
    </Upload>
  )
}

Solution

  • I finally found the answer:

    There is a field called showUploadList and you can set it to false, so it does not display the uploaded file.

    function UploadFile() {
      const [fileName, setFileName] = useState<string | null>()
      const [isModalVisible, setIsModalVisible] = useState(false)
    
      const onSelectFile = (file) => {
        setFileName(file.name)
        setIsModalVisible(true)
      }
    
      return (
        <>
          <Upload name="file" accept=".json" showUploadList={false} beforeUpload={onSelectFile}>
            <Button icon={<ImportIcon />} />
          </Upload>
          <Modal title="asdf" visible={isModalVisible} handleOk={undefined} handleCancel={undefined}>
            <p>{fileName ? `you selected ${fileName}` : 'no file selected'}</p>
          </Modal>
        </>
      )
    }