cancel
Showing results for 
Search instead for 
Did you mean: 

Displaying Files in UI5 from SAP DMS using SAP CAP

sahud
Participant

Hi All,

We are trying to view documents from SAP DMS in our UI5 application being streamed through the CAP service layer (node js). I have written a custom function that can return media type and a custom handler to get the file from a Gateway OData service and stream it to the UI. Please see details below:

The issue is I get a successful response back from the Gateway but the browser loads a empty page without any errors being logged.

cds definition for return

type Media {
        @Core.MediaType   : mediaType content : LargeBinary;
        @Core.IsMediaType : true mediaType    : String;
    }

    function getAttachment() returns Media;

Custom Handler to stream file back to UI - JS

/**Function to view attachment from DMS*/
    srv.on('com.ven.wom.ApiService.getAttachment', async (req, res,next)=>{try{
            console.log("==> Executing getAttachment() now");//let attachment =new Attachment();
            const fileURL ="/sap/opu/odata/sap/ZKMDOCUMENTS_SRV/Originals(DocumentType='T99',DocumentNumber='0000000000000010000001305',DocumentVersion='00')/$value";let JWT = await Utils.GetDataFromExternalServices.getJWT(req);let cookie = req._.req.headers.cookie;
            const response = await Attachment.Attachment.getAttachedFile(fileURL, JWT.authInfo, cookie);
            console.log("==> getAttachment ResponseCode: " + response.status + " - " + response.statusText);
            console.log("==> getAttachment Response: " + response.data);
            response.data.pipe(req._.req.res);
            response.data.pipe(res);}catch(error){
            console.error(error);next(err);}});

Finally the axios call to get the data from DMS:

         const request = {
            method: 'GET',
            url: `${url}`,
            headers: {
                'SAP-Connectivity-Authentication': `Bearer ${userToken}`,
                'Proxy-Authorization': `Bearer ${conn_access_token}`
            },
            proxy: {
                'host': conn_service.onpremise_proxy_host,
                'port': conn_service.onpremise_proxy_port
            },
            responseType: 'stream'
        };

        /**Add new Authorization for Basic Authnetication*/
        if (authentication === "basicauthentication") {
            let authToken = destinationDetails.authTokens[0];
            request.headers.Authorization = `${authToken.type} ${authToken.value}`;
        }

        try {
            console.info(request.method, 'odata', request.url);
            return axios(request);
        } catch (error) {
            console.log("==> Attachement.js: " + error)
            if (error.response) {
                request.error(400, "==> Attachement.js: " + error);
            } else {
                request.error(400, "==> Attachement.js: " + error);
            }
        }

The front-end app simply does a window.open() to the endpoint for displaying the file on the browser.

window.open("https://<valid-app-endpoint>/getAttachment()

The response I see on the browser is below - a empty page

When I check the log, the response from SAP is 200 and all the correct response headers are present:

Adding the above again as text for readibilit

{
  "set-cookie": [
    "sap-usercontext=sap-client=001; path=/",
    "MYSAPSSO2=AjQxMDMBABhTAEEASABVAEQAIAAgACAAIAAgACAAIAACAAYwADAAMQADABBOAE0ARAAgACAAIAAgACAABAAYMgAwADIAMQAwADEAMQA0ADAAOAAzADcABQAEAAAACAYAAlgACQACRQD%2fAVcwggFTBgkqhkiG9w0BBwKgggFEMIIBQAIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYIBHzCCARsCAQEwcDBkMQswCQYDVQQGEwJBVTEcMBoGA1UEChMTU0FQIFRydXN0IENvbW11bml0eTETMBEGA1UECxMKU0FQIFdlYiBBUzEUMBIGA1UECxMLSTAwMjA2NzE1OTYxDDAKBgNVBAMTA05NRAIICiAWERIhEwEwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTIxMDExNDA4MzczM1owIwYJKoZIhvcNAQkEMRYEFBzPGqBnuTNfNPFwEv%2fT8HrZi5eRMAkGByqGSM44BAMELzAtAhQO73GKqqqfui%2fXsljmxqyrjY%21BVQIVAI5cEwJOBeBQJTpJfY%21GR8HrDg7B; path=/; domain=.com",
    "SAP_SESSIONID_NMD_001=kcNLYYDaPbMC_4xr63JVAr8b0k9WQxHrqg8AFj4gQAI%3d; path=/"
  ],
  "content-type": "application/pdf",
  "content-length": "46512",
  "sap-metadata-last-modified": "Tue, 03 Sep 2019 23:39:23 GMT",
  "x-content-type-options": "nosniff",
  "content-disposition": "inline; filename=ABC_Test.pdf",
  "dataserviceversion": "2.0",
  "cache-control": "no-cache, no-store",
  "pragma": "no-cache",
  "server": "SAP NetWeaver Application Server / ABAP 731",
  "sap-server": "true"
}

I am not sure what;s happening here but I have used the same logic before with XSA to get documents from DMS and stream it to the UI and it has worked

Please let me know if I need to add any more details to this.

Appreciate any help.

Thanks.

Best Regards,

Deepak Sahu

sparihar11
Explorer
0 Kudos

sahud Were you able to get the image on UI5? I am having a similar requirement could you please help?

sahud
Participant
0 Kudos

Hi shilpa.parihar ,

Unfortunetely, we could not figure this out from the documents being pulled through from DMS via CAP layer. For no, we are directly connecting the UI5 applications to the Gateway service using destination to display the documents to the user. I will post an update when we complete the solution of displaying media via CAP layer.

Hope this helps.

Best Regards,

Deepak Sahu

Accepted Solutions (0)

Answers (2)

Answers (2)

david_kunz2
Advisor
Advisor

Hi Deepak,

To return a stream in your custom handler, you should not modify the _req object (it's the internal express req object).

Instead, you should return

return {
value: yourStream,
'*@odata.mediaContentType': yourType
}

We'll update the docu accordingly.

Best regards,

David

sahud
Participant
0 Kudos

Hi David,

I tried the above bit of code but I see the below page displayed when trying to display a image/png file.

From the UI, I simply try to access the same URL invoking the CAP function to display attachment . Should we be doing something different in the UI to render the image. we want to image to be opened in a new browser tab for the user to view it.

window.open("https://localhost:5000/getAttachment()


I have updated the code as per below:

api-service.cds

namespace com.test.app;

service ApiService {

    type Media {
        @Core.MediaType   : mediaType value : LargeBinary;
        @Core.IsMediaType : true mediaType    : String;
    }

    function getAttachment() returns Media;
}

api-service.js --> getAttachment()

const Attachment = require('./libs/Attachment');
var fs = require('fs');

module.exports = (srv) => {
    /** Function to download attachment from DMS*/
    srv.on('com.ven.wom.ApiService.getAttachment', async (req, res, next) => {
        try {
            console.log("==> Executing getAttachment() now");
            let docNo = req.data.DocumentNumber;
            // let attachment = new Attachment();
            const fileURL = `/sap/opu/odata/sap/ZKMDOCUMENTS_SRV/Originals(DocumentType='T99',DocumentNumber='0000000000000010000008776',DocumentVersion='00')/$value`;
            console.log("==> file URL:" + fileURL);
            let JWT = await Utils.GetDataFromExternalServices.getJWT(req);
            let cookie = req._.req.headers.cookie;
            const response = await Attachment.Attachment.getAttachedFile(fileURL, JWT.authInfo, cookie);
            console.log("==> getAttachment ResponseCode: " + response.status + " - " + response.statusText);
            console.log("==> Response headers: " + JSON.stringify(response.headers));
            console.log("==> getAttachment Response: " + response.data.toString('utf-8'));

            return {
                value: response.data,
                '*@odata.mediaContentType': "image/png"
            }
        } catch (error) {
            console.error(error);
            req.error(500, error);
        }
    });
}

Thanks.

Deepak

iashishsingh
Participant
0 Kudos

Hi sahud,

Were you able to resolve this?

Hi david.kunz2,

Is there an example of this scenario where a service function allows download of a file?

Thanks!

david_kunz2
Advisor
Advisor
0 Kudos

Hi Ashish,

An example for that will be provided in the documentation soon.

Best regards,
David

gregorw
Active Contributor
0 Kudos

In the meantime you chan checkout my example in bookshop-demo/srv/dms-service.js