StreamResources with byte[]

Hi! I am currently working on a Spring Boot /Vaadin application which receives some data via a rest endpoint and then successfully updates the UI with a Broadcaster, as suggested in the Vaadin Documentation. Among the received data is an attachment as byte array which I am struggling to display in an IFrame with StreamResource:

`Attachment attachment = this.outgoingReq.getResponse().getAttachmentList().get(0);
String fileExtension = MimeTypeParser.safeParseMimeType(attachment.getMimeType()).getContentSubType(); //is pdf
StreamResource resource = new StreamResource(
“attachment.” +fileExtension, () → new ByteArrayInputStream(attachment.getAsByteArray()));
StreamRegistration registration = VaadinSession.getCurrent().getResourceRegistry().registerResource(resource);

IFrame iframe = new IFrame(registration.getResourceUri().toString());
iframe.addClassName(“iframe”);
iframe.setSizeFull();
div.add(iframe);``

This however shows the following error in the browser

`Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Sep 20 13:22:31 CEST 2022
There was an unexpected error (type=Not Found, status=404).
Resource is not found for path=VAADIN/dynamic/resource/0/5cd2f4c5-ee35-45ec-b098-3abadf4d5ebf/attachment.pdf`

On the other hand, writing the byte array into a local file with apache commons works as expected
FileUtils.writeByteArrayToFile(new File("pathname.pdf"), attachment.getAsByteArray());

I have used the StreamResource in a similar way and it worked. What am I doing wrong now? Can someone point me in the right direction? Many thanks

I don’t think this is the intended way.

Two possible solutions that I come up with:

  • create a Rest Endpoint where the file content is returned
  • pass the base64 encoded byte array to the iframe

thanks :smile: this makes sense. however, i can t seem to find a way to pass the base64 encoded array to the iframe… any tips? thanks

If I remember correctly you can pass it as URL to it like “data:image/gif;base64,AAAA”

You can find example URLs here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs

thank you loads, i ll give it a go :smile:

:slightly_smiling_face: i m making progress and it seems to at least somehow work. it renders a gibberish document now. thanks again

Update: I ended up using this pdf viewer which also works with the data urls “data:application/pdf”+“;base64,” + byteToString https://vaadin.com/directory/component/pdf-viewer . Can’t thank you enough @quirky-zebra