javascriptreactjsmaterial-uidownloadcreateobjecturl

Material-UI: Chip component download option is not working, how to resolve the download issue?


I have uploaded the file using UI and I want to download after some time or instantly and I have implemented the same using <Chip> component but it not working, need help to resolve the same.

**uploaded file: **

const data = {
  lastModified: 1701069121191,
  lastModifiedDate: Mon Nov 27 2023 12:42:01 GMT+0530 (India Standard Time) {},
  name: "Template_v2(1).xlsx",
  size: 91827,
  type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  webkitRelativePath: ""
}

Component:

<Chip {...{
  label: d.name,
  onClick: () => <a href={URL.createObjectURL(d)} download style="display: none">shouldnt be visible</a>,
  onDelete: () => {
      onAttachChange({
          attachments: row.attachments.filter(f => f.name !== d.name),
          rowIndex: rowIndex
      })
  }
}} />

Solution

  • I found issue that we are not called <a> click method to download file and fixed in the following way

    solution: we have created <a> elemlent using Javascript and called click() method

    <Grid
        container
        spacing={2}
        alignContent={'stretch'}
        className={classes.rowsGridPadding}
    >
        {
            row.attachments.length > 0 ? (row.attachments.map((d, i) => {
                return <Grid item sx={{ alignItems: 'flex-start' }} key={`${d.name}${i}`}>
                    <Chip {...{
                        label: d.name,
                        onClick: () => {
                            const link = document.createElement('a')
                            link.download = d.name
                            link.href = URL.createObjectURL(d)
                            link.click() // we have called click() method
                        },
                        onDelete: () => {
                            onAttachChange({
                                attachments: row.attachments.filter(f => f.name !== d.name),
                                rowIndex: rowIndex
                            })
                        }
                    }} />
                </Grid>
            })) : <Grid item sx={{ alignItems: 'flex-start' }}>No Attachments Found</Grid>
        }
    </Grid>