How to show fileDescriptor (files: images, pdf or any files) in React front module

Hi…
i want the fileDescriptor to be opened in the react front module. That is the Attached images in the file descriptor…
Please guide me to resolve this issue

Thanks…

1 Like

Hi @Narayanan,

You can use CUBA REST JS .getFile() to download the file:

getCubaREST().getFile(fileId).then((blob: Blob) => {
  // do something with the Blob

  // for example, you can open an image or pdf in a new browser tab
  const objectUrl: string = URL.createObjectURL(blob);
  window.open(objectUrl);

  // or you can download the file
  // we are creating an anchor here in order for the downloaded file to have a correct name
  const anchor: HTMLAnchorElement = document.createElement('a');
  anchor.href = objectUrl;
  anchor.download = fileName;
  anchor.click();

  // cleanup
  URL.revokeObjectURL(objectUrl);
});

Regards,
Vyacheslav

Hi @v.pushkin,

I´m trying to display image of a entity Card inside my aplication using this approach that you proposed.

Im passing the FileDescriptor ID to a function that returns the component for product card like the code bellow. The problem is that the image is never displayed. I’m new to REACT and any suggestion would help me a lot…

renderCard(e:Produto){
    return(
      <div>
        <Card
            title={e.nome}
            key={e.id ? getStringId(e.id) : undefined}
            style={{ marginBottom: "12px" }}
          >
            <div className="carddata">
              {this.renderImage(e.image?.id!)}
            </div>
          </Card>
      </div>
    )
  }

   renderImage(imageId:string){
     let imgPath:string = ""; 

      getCubaREST()?.getFile(imageId).then((blob: Blob) => {
        imgPath = URL.createObjectURL(blob);
      });

      return(
        <div>
          <Image src={imgPath} alt="not available.."/>
        </div>  
      )  
   }

Hi @nathanmachado,

This is because getCubaREST()?.getFile() is async, so when renderImage returns, imgPath is still an empty string. You need to provide means for component to re-render once imgPath is updated.

You can see an example of how it can be done in Frontend UI: FileUpload creates an object URL and makes it a MobX observable, then passes it as a prop to ImagePreview component.

1 Like

I did it and worked perfectly! Thankyou very much.