Skip to Content
Technical Articles
Author's profile photo Thajunniza M A

Media in SAP Cloud Application Programming Model(CAP)

In this post, I’m going to show how to store media data in SAP HANA DB using SAP Cloud Application Programming Model(CAP) and UI5.

Prerequisites:

Need to know how to create a basic CAP project and adding a UI to it using SAP Business Application Studio.

  • Create a CAP project-Media

  • Create an entity for media named ‘MediaFile’ in data/data-model.cds. Here two annotations are important.
    • @Core.MediaType – It denotes the data element contains media data.
    • @Core.IsMediaType – It denotes the data element contains a MIME type.
    • namespace Media.db;
      
      entity MediaFile {
          key id        : Integer;
              @Core.MediaType   : mediaType
              content   : LargeBinary;
              @Core.IsMediaType : true
              mediaType : String;
              fileName  : String;
              url       : String;
      };
  • Create a service in srv->media-service.cds to expose the MediaFile Entity.
using {Media.db as db} from '../db/data-model';


service MediaService @(path : '/media') {
    entity MediaFile as projection on db.MediaFile;
};
  • In srv->media-service.js add below logic on the hook handlers
    • On before create handler we will generating the url for the uploaded content which is used to view the content in browser.
    • And we also need to add custom logic in read handler to view the uploaded content in the browser.
    • I have used sequence to generate the ID.
const SequenceHelper = require("./library/SequenceHelper");
const { Readable, PassThrough } = require("stream");
const cds = require('@sap/cds');
cds.env.features.fetch_csrf = true

module.exports = cds.service.impl(async function () {

    const {
        MediaFile
    } = this.entities;


    /**
     * Handler method called before creating data entry
     * for entity Mediafile.
     */
    this.before('CREATE', MediaFile, async (req) => {
        const db = await cds.connect.to("db");
        // Create Constructor for SequenceHelper 
        // Pass the sequence name and db
        const SeqReq = new SequenceHelper({
            sequence: "MEDIA_ID",
            db: db,
        });
        //Call method getNextNumber() to fetch the next sequence number 
        let seq_no = await SeqReq.getNextNumber();
        // Assign the sequence number to id element
        req.data.id = seq_no;
        //Assign the url by appending the id
        req.data.url = `/media/MediaFile(${req.data.id})/content`;
    });

    /**
     * Handler method called on reading data entry
     * for entity Mediafile.
     **/
    this.on("READ", MediaFile, async (req, next) => {
        if (!req.data.id) {
            return next();
        }
        //Fetch the url from where the req is triggered
        const url = req._.req.path;
        //If the request url contains keyword "content"
        // then read the media content
        if (url.includes("content")) {
            const id = req.data.id;
            var tx = cds.transaction(req);
            // Fetch the media obj from database
            var mediaObj = await tx.run(
                SELECT.one.from("Media.db.MediaFile", ["content", "mediaType"]).where(
                    "id =",
                    id
                )
            );
            if (mediaObj.length <= 0) {
                req.reject(404, "Media not found for the ID");
                return;
            }
            var decodedMedia = "";
            decodedMedia = new Buffer.from(
                mediaObj.content.toString().split(";base64,").pop(),
                "base64"
            );
            return _formatResult(decodedMedia, mediaObj.mediaType);
        } else return next();
    });

    function _formatResult(decodedMedia, mediaType) {
        const readable = new Readable();
        const result = new Array();
        readable.push(decodedMedia);
        readable.push(null);
        return {
            value: readable,
            '*@odata.mediaContentType': mediaType
        }
    }

 

UI to upload the file

  • Add a UI application in your CAP project and create OData model for the above cap service.
  • In the View code to add a File uploader ui and a button to trigger file upload action.

 

<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:u="sap.ui.unified" controllerName="com.ta.mediaui.controller.mediaUpload" displayBlock="true">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="{i18n>title}">
                    <content>
                        <FlexBox direction="Column" class="sapUiLargeMargin">
                            <Label text="Attach File" labelFor="fileUploader" required="true"/>
                            <u:FileUploader id="__fileUploader" tooltip="Upload your file to DB"/>
                            <Button text="Upload" press="onUploadFile" type="Emphasized"/>
                        </FlexBox>
                    </content>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

 

  • In Button Action add the below logic to upload the file in the SAP HANA DB through CAP.
  • As a first step, create an entity without media data using a CREATE request. After creating the entity, you can insert a media property using the UPDATE method.

 

// @ts-nocheck
sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageBox"
],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Controller, MessageBox) {
        "use strict";

        return Controller.extend("com.ta.mediaui.controller.mediaUpload", {
            onInit: function () {
            },

            _getBaseURL: function () {
                var oBaseUrl = this.getOwnerComponent().getManifestEntry("/sap.app/id").replaceAll(".", "/");
                return jQuery.sap.getModulePath(oBaseUrl)
            },
            /**
             * On File Upload
             */
            onUploadFile: function () {
                var oUploadSet = this.byId("__fileUploader");
                //Upload image
                var domRef = oUploadSet.getFocusDomRef();
                var file = domRef.files[0];
                this.file = file;
                var reader = new FileReader();
                reader.onload = function (oEvent) {
                    // get an access to the content of the file
                    this.content = oEvent.currentTarget.result;
                    this.createfile();
                }.bind(this);
                reader.readAsDataURL(file);

            },

            /**
             *  Create Operation to create an entry in CAP
             */
            createfile: function () {
                var that = this;
                // Data for CAP to create entry
                var oImageData = {
                    "mediaType": this.file.type,
                    "fileName": this.file.name
                };
                var oCAPModel = this.getOwnerComponent().getModel("oCAPModel");
                var sURL = "/MediaFile";
                //Create call for CAP OData Service
                oCAPModel.create(sURL, oImageData, {
                    success: function (oData, oResponse) {
                        var id = oData.id;
                        that.updateMedia(id);
                    },
                    error: function (jqXHR, textStatus) {

                    },
                });
            },

            /**
             *  Update Media Type 
             */
            updateMedia: function (id) {
                var that = this;
                // Data for CAP to create entry
                var oImageData = {
                    "content": this.content
                };
                var oCAPModel = this.getOwnerComponent().getModel("oCAPModel");
                var sURL = `/MediaFile(${id})/content`;
                //Create call for CAP OData Service
                oCAPModel.update(sURL, oImageData, {
                    method: "PUT",
                    success: function (oData, oResponse) {
                        var sMsg = "File Uploaded Successfully for ID: " + id;
                        MessageBox.success(sMsg);
                    },
                    error: function (jqXHR, textStatus) {

                    },
                });
            },

        });
    });

 

Results:

  • UI Screen to upload the document.I have uploaded a pdf called dummy.pdf

 

  • The data stored in CAP

  • Media file in browser

 

 Conclusion:

From this blog we are able to understand how SAP Cloud Application Programming Model(CAP) provides out-of-the-box support for serving media and other binary data.

However, you can use it to make much more elaborate changes to your applications.

I would love to hear from you! Please leave your feedback below.

Assigned Tags

      5 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Vishal Kumar
      Vishal Kumar

      Hello Thajunniza,

      Will this also work incase of jpg/photo media file ?

      Regards,

      Vishal Kumar

      Author's profile photo Thajunniza M A
      Thajunniza M A
      Blog Post Author

      Hi Vishal,

      Yes its works for image as well.

       

      Regards,

      Thaj

      Author's profile photo Siddhant Kumar
      Siddhant Kumar

      Hello Thajunniza,

      For me its oCapmodel.create or update is not a function.

      Regards,

      Siddhant Kumar

      Author's profile photo Thajunniza M A
      Thajunniza M A
      Blog Post Author

      Have you defined the oCapmodel in manifest.json

      Author's profile photo Siddhant Kumar
      Siddhant Kumar

      Hi Thajunniza,

       

      yes i have defined in oCapmodel in manifest json thank you.

       

      But PUT request is giving error while updating file.

      The error is Method PATCH not allowed for PRIMITIVE.PROPERTY.