Return File from Service

I’m working on generating Reports and sending them back to the Polymer client, but I can’t figure out how to return the generated report.

What I’ve got so far

Java

I’ve been working based off the example outlined in the YARG GitHub repo’s examples, but it doesn’t seem to contain all the info I need.
After building the report, I tried finishing the service method with:

A byte[]:

return reporting
            .runReport(new RunParams(report))
            .getContent();

An instance of File:

File file = new File("result.pdf");
try (FileOutputStream fileOutputStream = new FileOutputStream(file);) {
    fileOutputStream.write(reporting
            .runReport(new RunParams(report))
            .getContent()
    );
} catch (IOException ioe) {
    throw ...;
}
return file;

The file was saved properly, and I could open result.pdf manually with satisfactory results, but the response to my Javascript was less than satisfactory.

Javascript

cuba.getApp()
  .invokeService(<<Service Name>>, <<Method Name>>, <<Params>>, {
    handleAs: "blob"
  })
  .then(response => console.log(response))
  .catch(error => console.error(error))

When returning a byte[] from Java:

I received a nice and jumbled blob, which looked right (albeit much shorter than I thought it would be), but I couldn’t figure out how to read it.

When returning an instance of File from Java:

Unfortunately, the code didn’t do as I hoped. The response from the server was {"path":"result.pdf"}.

Finally

How can I return a file from a service method properly? And any pointers on how to read/view/download that file with Javascript?

Hi Caden,

Working with files is not supported in REST API services.

You should either create custom controller or use File Storage and special REST API methods

See the example of report generation/download from Polymer client in the following repo: GitHub - aleksey-stukalov/sample-report-generation: The sample shows how to use reporting add-on in the CUBA Platform (requires premium package)

1 Like

That’s too bad! But I think your approach is leading me down a better path than I was originally considering. I was hoping to return a file without saving it to the server, but with the method you outlined that doesn’t seem to be possible. Instead, I think I will use your code (albeit slightly modified) and store the files for future access, which might be appreciated by the client.

Thanks for your help!