cancel
Showing results for 
Search instead for 
Did you mean: 

Download File on Action in CAP / Java Application

dvalasek
Explorer
328

Hello, I am developing a CAP application with Java/Spring Boot and I ran into a problem I have been stuck on.

I have a defined an action within my entity that should fetch details from S4HC, assemble a CSV file from it and then return the CSV to the user. I implemented the action handler that fetches the data and assembles the csv file into byte[] but now I have no idea how to actually make it so that the file is downloaded by the user to their machine.
My action returns a LargeBinary 

dvalasek_0-1730805184918.png

but at the end of the handler, when i set the context (that expects byte[]) as that file, nothing happens.
I couldnt find anywhere online a solution for this. Can anyone assist please in how the implementation should look like ?

 

View Entire Topic
catano
Active Participant

Hi @dvalasek ,

I haven't tried, but I would give it a shot in the following way if you already have your method implemented:

  • check if model follows Serving Media Data
  • add on On event handler for the READ method on your entity in the same way as described in Custom Streaming (Node beta), check if the media type element in question is requested, if yes, return the stream with the method you just created, otherwse continue processing
  • build and test with the following URL pattern: /YourEntity(<ID>)/MediaTypeElement as described in Reading Media Resources

In the documentation the custom streaming topic is only for Node and it is in beta currently. I tested the Node.js version with a basic scenario and it worked for me with @sap/cds: 8.4.0

Regards,
Peter

dvalasek
Explorer
0 Kudos
Thank you for your input and you may very well be right, but I am not having any luck. I am at the beginning on my CAP learning journey at some of the concepts in Java are tough for me to really grasp. So i was hoping that someone could show me the full implementation in Java. The file it is supposed to return to download is not even a part of the entity (I dont want it saved in the db) so I would just like to fetch the data from S4HC and directly send it to frontend to download after it has been processed. So i return the byte[] in my action handler and in the browser i can see it base64 encoded in the response, but it wont trigger a download even if i try some other workarounds and manually injecting headers into the response.
catano
Active Participant
0 Kudos

Hi @dvalasek ,

Could you try to add the property to your entity - just for testing purposes -, and serve the byte[] in the On READ handler of the entity in question if the media property is requested? (e.g.: /Entity(ID)/mediaProperty)
Just to check if the method is working.

If it works, it means that you can serve media at least.
I think you can mark the property as virtual in your model if you want to tell that you don't want to persist it.

Regards,
Peter