Skip to Content
Author's profile photo Himanshu Pensia

Media Handling in OData in SAP UI5

Scenario:

We will be creating OData for creating and reading Media files and consume it in SAPUI5 application.

Prerequisites:

  1. A trial account on SAP Cloud Platform with Web IDE Service enabled.
  2. Destination to On premises system is maintained in the SAP Cloud Platform
  3. Hana Cloud Connector should be in active state.
  4. Component IW_FND and IW_BEP both have to be at least on SAP Net Weaver Gateway 2.0 SP09 or component SAP_GWFND is on SAP Net Weaver 7.40 SP08.
  5. Active security session management.
  6. Currently, URLs containing segment parameters such as; mo ;o, or ;v=.. Cannot be processed in the soft-state processing mode.

Step-by-Step Procedure:

  1. Creating the Odata Service.
  2. Register the Odata Service and test it from Gateway.
  3. Consume the Odata Service in UI5 Application.

STEP 1:  Creating the Odata Service

  1. Create Table in SE11. (You may put any name as you like, i have used name ZFILE for the Table).
  2. Goto SEGW, Create OData project, import your table (ZFILE) from DDIC structure to create ENTITY_TYPE.
  3. Select the entity type “ZFILE” you just created and Choose the check box media as selected.
  4. Now generate Runtime Artifacts and Redefine the DEFINE method of the model provider extension call.
    method DEFINE.
          super->define( ).
    
    Data: lo_entity TYPE REF TO /iwbep/if_mgw_odata_entity_typ,
    
    lo_property TYPE REF TO /iwbep/if_mgw_odata_property.
    
    lo_entity = model->get_entity_type( iv_entity_name = 'ZFILE' ).
    
    IF lo_entity IS BOUND.
    
    lo_property = lo_entity->get_property( iv_property_name = 'Filename').
    
    lo_property->set_as_content_type( ).
    
    ENDIF.
      endmethod.
    ​
  5. Click on the Methods tab and redefine the method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_STREAM .
    method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_STREAM.
    
    data: lw_file type zfile.
    field-symbols:<fs_key> type /iwbep/s_mgw_name_value_pair.
    read table it_key_tab assigning <fs_key> index 1.
    lw_file-filename = iv_slug.
    lw_file-value    = is_media_resource-value.
    lw_file-mimetype = is_media_resource-mime_type.
    lw_file-sydate  = sy-datum.
    lw_file-sytime  = sy-uzeit.
    
    insert into zfile values lw_file.
    
    endmethod.​
  6. Now click on the Methods tab and redefine the method  /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_STREAM .
    method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_STREAM.
    
    data :  ls_stream  type ty_s_media_resource,
    
    ls_upld    type zfile.
    
    lv_filename type char30.
    
    field-symbols:<fs_key> type /iwbep/s_mgw_name_value_pair.
    
    read table it_key_tab assigning <fs_key> index 2.
    lv_filename = <fs_key>-value.
    select single * from zfile into ls_upld where filename = lv_filename.
    if ls_upld is not initial.
    ls_stream-value = ls_upld-value.
    ls_stream-mime_type = ls_upld-mimetype.
    copy_data_to_ref( exporting is_data = ls_stream   changing  cr_data = er_stream ).
    
    endif.
    
    endmethod.​
  7. Now click on the Methods tab and redefine the method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_STREAM.
    method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_STREAM.
    
    data: lw_file type zfile.
    field-symbols:<fs_key> type /iwbep/s_mgw_name_value_pair.
    
    read table it_key_tab assigning <fs_key> index 1.
    lw_file-filename = <fs_key>-value.
    lw_file-value    = is_media_resource-value.
    lw_file-mimetype = is_media_resource-mime_type.
    lw_file-sydate  = sy-datum.
    lw_file-sytime  = sy-uzeit.
    modify zfile from lw_file.
    
    endmethod.
    ​
  8. Now click on the Methods tab and redefine the method FILESET_GET_ENTITYSET.

    METHOD fileset_get_entityset.
      DATA:
          it_final   TYPE STANDARD TABLE OF zfile,
          lt_filters TYPE                   /iwbep/t_mgw_select_option,
          ls_filter  TYPE                   /iwbep/s_mgw_select_option,
          ls_so      TYPE                   /iwbep/s_cod_select_option,
          p_name     TYPE c LENGTH 15.
    
      SELECT
        mandt
        filename
        SYDATE
        SYTIME
        VALUE
        MIMETYPE
    
      FROM zfile
      INTO TABLE et_entityset.
    
      ENDMETHOD.
    ​

STEP 2:  Register the Odata Service

  1. Register the Odata service to the Gateway server.
  2. Open the Odata service with SAP Gateway Client.
  3. Check get stream method with following URL (Will be used for downloading purpose) .
    /sap/opu/odata/sap/ZFILE_SRV/FILESet(Mandt=’200′,Filename=’mobile1.jpg’)/$value.
  4. Check create stream method with following URL (Will be used for uploading purpose).
    /sap/opu/odata/sap/ZFILE_SRV/FILESet
    Select the Post Radio button and select the FILESet Entity Set. Select “Add File” button and choose the File to be uploaded.Click on “Add Header” button and enter the value of header.Enter value SLUG in Header Name.Enter name of the file in Header Value.
    NOTE : Response of the URL may contain following error, but this should not cause any problem. The file is uploaded successfully. 

STEP 3: Consume the Odata Service in UI5 Application.

  1. Go to SAP Web IDE, and create a new project with UI5 application template.(assuming that name of view and controller is VIEW1)
  2. Open the view1.view.xml file and put below code there.
    <mvc:View xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:u="sap.ui.unified" controllerName="File_Upload.controller.View1" displayBlock="true">
    <App>
    <pages>
    <Page title="Upload The File">
    <content>
    
    <Label text="Put your Documents here" width="100%" id="__label0"/>
    <u:FileUploader id="fileUploader" useMultipart="false" name="myFileUpload" uploadUrl="/destinations/TRN/sap/opu/odata/sap/ZFILE_SRV/FILESet" width="400px" tooltip="Upload your file to the local server" uploadComplete="handleUploadComplete"/>
    <Button text="Upload File" press="handleUploadPress"/>
     
    <List id="itemlist" headerText="Files" class="sapUiResponsiveMargin" width="auto" items="{ path : 'Data>/FILESet' }">
    <items>
    <ObjectListItem id="listItem" title="{Data>Filename}">
    <ObjectAttribute text="Download" active="true" press="fun"/>
    </ObjectListItem>
    </items>
    </List>
    </content>
    </Page>
    </pages>
    </App>
    </mvc:View>​
  3. Open the view.controller.js file and put below code there.
    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/model/Filter",
        "sap/ui/model/FilterOperator",
        "sap/ui/model/odata/ODataModel",
        "sap/m/MessageToast",
        "sap/m/Button",
        "sap/m/Dialog",
        "sap/m/MessageBox",
        "sap/m/List",
        "sap/m/StandardListItem"
    ], function(Controller, Filter, FilterOperator, ODataModel, MessageToast, Button, Dialog, MessageBox, List, StandardListItem) {
        "use strict";
    
    
    
        var name;
        var mandt;
    
        var oModel = new sap.ui.model.odata.ODataModel("Put path of Odata with destination Here");
        return Controller.extend("File_Upload.controller.View1", {
            handleUploadComplete: function() {
                sap.m.MessageToast.show("File Uploaded");
                var oFilerefresh = this.getView().byId("itemlist");
                oFilerefresh.getModel("Data").refresh(true);
                sap.m.MessageToast.show("File refreshed");
    
            },
            handleUploadPress: function() {
                var oFileUploader = this.getView().byId("fileUploader");
                if (oFileUploader.getValue() === "") {
                    MessageToast.show("Please Choose any File");
                }
                oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                    name: "SLUG",
                    value: oFileUploader.getValue()
                }));
                oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                    name: "po",
                    value: "12234"
                }));
    
                oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                    name: "x-csrf-token",
                    value: oModel.getSecurityToken()
                }));
                oFileUploader.setSendXHR(true);
    
                oFileUploader.upload();
    
    
    
            },
            fun: function(oEvent) {
                var ctx = oEvent.getSource().getBindingContext("Data");
                name = ctx.getObject().Filename;
                mandt = ctx.getObject().Mandt;
                var oModel = new sap.ui.model.odata.ODataModel("Put path of Odata with destination Here");
                oModel.getData("/Data");
                oModel.read("/FILESet(Mandt='" + mandt + "',Filename='" + name + "')/$value", {
    
                    success: function(oData, response) {
                        var file = response.requestUri;
                        window.open(file);
    
                    },
                    error: function() {
    
    
                    }
                });
    
            },
    
        });
    });​

 

Assigned Tags

      18 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Saravanan Madhappan
      Saravanan Madhappan

      Nice one Himanshu. Thanks for sharing.

      Author's profile photo Venkatesh Machineni
      Venkatesh Machineni

      Nice one,

      I am getting 405 method not allowed error.

      Thanks,

      Venkatesh.

      Author's profile photo Himanshu Pensia
      Himanshu Pensia
      Blog Post Author

      Hi Venkatesh,

      Please check this link related to above error.

      If u still not able to resolve the problem then please describe the error in detail.

      Thanks,

      Himanshu

       

      Author's profile photo Saswata Chandra
      Saswata Chandra

      I'm using UI5 application fileUploader control and selecting an .xls file. After firing the - upload() function, I'm receiving 405 method not allowed error.
      I initially observed the Content-Type in header must be - 'application/vnd.ms-excel' and added that as a request header parameter, but still no luck.

      Could you please guide?

      Author's profile photo Saswata Chandra
      Saswata Chandra

      I'm pretty late here in the comment but I assume you solved this 405 error. Could you please guide? I'm receiving exactly the same error after following this blog.

      Author's profile photo Debabrata Behera
      Debabrata Behera

      Hi Himanshu,

      It is  a very helpful post but I am getting the below error Could you please help me on the same.

      My View

      <mvc:View controllerName=”FileUploadingZFileUpload.controller.View1″
      xmlns:html=”http://www.w3.org/1999/xhtml” xmlns:mvc=”sap.ui.core.mvc”
      displayBlock=”true” xmlns=”sap.m” xmlns:u=”sap.ui.unified” >
      <App>
      <pages>
      <Page title=”Upload The File”>
      <content>
      <Label text=”Put your Documents here” width=”100%” id=”__label0″ />
      <u:FileUploader id=”fileUploader” useMultipart=”false”
      name=”myFileUpload” uploadUrl=”/sap/opu/odata/sap/ZSD_ORDER_FIORI_SRV/FileLoadSet”
      width=”400px” tooltip=”Upload your file to the local server”
      uploadComplete=”handleUploadComplete” />
      <Button text=”Upload File” press=”handleUploadPress” />

      <List id=”itemlist” headerText=”Files” class=”sapUiResponsiveMargin”
      width=”auto” items=”{ path : ‘Data>/FileLoadSet’ }”>
      <items>
      <ObjectListItem id=”listItem” title=”{Data>Filename}”>
      <ObjectAttribute text=”Download” active=”true”
      press=”fun” />
      </ObjectListItem>
      </items>
      </List>
      </content>
      </Page>
      </pages>
      </App>
      </mvc:View>

       

      My Controller 

       

      sap.ui.define([
      “sap/ui/core/mvc/Controller”,
      “sap/ui/model/Filter”,
      “sap/ui/model/FilterOperator”,
      “sap/ui/model/odata/ODataModel”,
      “sap/m/MessageToast”,
      “sap/m/Button”,
      “sap/m/Dialog”,
      “sap/m/MessageBox”,
      “sap/m/List”,
      “sap/m/StandardListItem”
      ], function(Controller, Filter, FilterOperator, ODataModel, MessageToast, Button, Dialog, MessageBox, List, StandardListItem) {
      “use strict”;

      var name;
      var mandt;
      var oModel = new sap.ui.model.odata.ODataModel(“/sap/opu/odata/sap/ZSD_ORDER_FIORI_SRV/”);

      return Controller.extend(“FileUploadingZFileUpload.controller.View1”, {

      onAfterRendering: function() {

      jQuery(“#__page0-intHeader-BarPH”).css(“background-color”, “yellow”);
      },

      handleUploadComplete: function() {
      sap.m.MessageToast.show(“File Uploaded”);
      var oFilerefresh = this.getView().byId(“itemlist”);
      oFilerefresh.getModel(“Data”).refresh(true);
      sap.m.MessageToast.show(“File refreshed”);

      },

      handleUploadPress: function() {
      var oFileUploader = this.getView().byId(“fileUploader”);
      if (oFileUploader.getValue() === “”) {
      MessageToast.show(“Please Choose any File”);
      }
      oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
      name: “SLUG”,
      value: oFileUploader.getValue()
      }));
      oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
      name: “po”,
      value: “12234”
      }));

      oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
      name: “x-csrf-token”,
      value: oModel.getSecurityToken()
      }));
      oFileUploader.setSendXHR(true);

      oFileUploader.upload();

      },
      fun: function(oEvent) {
      var ctx = oEvent.getSource().getBindingContext(“Data”);
      name = ctx.getObject().Filename;
      mandt = ctx.getObject().Mandt;
      var oModel = new sap.ui.model.odata.ODataModel(“/sap/opu/odata/sap/ZSD_ORDER_FIORI_SRV”);
      oModel.getData(“/Data”);
      oModel.read(“/FileLoadSet(Mandt='” + mandt + “‘,Filename='” + name + “‘)/$value”, {

      success: function(oData, response) {
      var file = response.requestUri;
      window.open(file);

      },
      error: function() {

      }
      });

      }

      });
      });

       

      Error In Consle.

      1.[ODataMetadata] initial loading of metadata failed .

      2.Failed to load    http://uk1gcnsd31701.corpnet2.com:8080/sap/opu/odata/sap/ZSD_ORDER_FIORI_SRV/$metadata  : Response to preflight request doesn't passaccess control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63525' is therefore not allowed access. The response had HTTP status code 401.

      3. Uncaught TypeError: Cannot read property 'refresh' of undefined View1.controller.js?eval:32

       

       

       

      Author's profile photo Adam Rafinski
      Adam Rafinski

      Thx for the great post and sharing.
      Some helpful notes on this the post for abap noobs like myself:

      4.) you do in MPC_EXT
      5-8.) youi do in DPC_EXT

      Code of 6 contains typo, replace '.' with ',' in line3:

      ls_upld type zfile.

      needs to become

      ls_upld type zfile,

      in order for it to work

      Author's profile photo B@lu .
      B@lu .

      hi Himanshu,

      first of all thanks for creating such a useful blog .

      i have one doubt at GET_STREAM method implementation

      at the end of the implementation finally we are creating a data object referancing to type ty_s_media_source.

      how exactly you know that with this type we have to create a data object and pass it to ER_STREEM?

       

      Author's profile photo Dharmesh Kumar
      Dharmesh Kumar

      Excellent post, good work Himanshu??

      Author's profile photo Avinash Sahoo
      Avinash Sahoo

      Hi Himanshu,

       

      Can i use this '/$value' in Odata V2 Model?

      Author's profile photo Himanshu Pensia
      Himanshu Pensia
      Blog Post Author

      Yes Avinash,

      You can use ‘/$value’ in Odata V2 Model.

      Author's profile photo Kameswara Gonugunta
      Kameswara Gonugunta

      Hi Himanshu ,

       

      Is that possible to upload .pdf and .xls etc mime types .

       

      If yes is there a size limit .  Please let me know

      Thanks

      Kamesh

      Author's profile photo Sayantani Sensharma
      Sayantani Sensharma

      While uploading a pdf file, I am getting "mutipart/form-data" in is_media_resource-mimetype in the CREATE_STREAM method in ODATA. How do I convert this to pdf again to store it in the archiving repository in the correct format?

      Author's profile photo rahhaoui mohamed
      rahhaoui mohamed

      Hi,

      In my CREATE_STREAM method the IV_SLUG parameter is always empty.

      Could you please help me?

      sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/core/Item",
        "sap/ui/model/json/JSONModel",
        "sap/m/upload/Uploader",
        "sap/m/ObjectMarker",
        "sap/m/MessageToast",
        "sap/m/UploadCollectionParameter",
        "sap/ui/unified/FileUploaderParameter",
        "sap/ui/core/format/FileSizeFormat",
        "sap/m/library",
        "sap/ui/core/Fragment",
        "sap/m/Image"
      ], function (Controller, MessageToast) {
        "use strict";
            var oModel = new sap.ui.model.odata.ODataModel("/sap/opu/odata/sap/ZHR_INT_ALLOWANCE_SRV");
        return Controller.extend("generated.app.controller.Main", {
          handleUploadComplete: function (oEvent) {
          sap.m.MessageToast.show("File Uploaded");
            var sResponse = oEvent.getParameter("response");
            if (sResponse) {
              var sMsg = "";
              var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
              if (m[1] === "200") {
                sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
                oEvent.getSource().setValue("");
              } else {
                sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
              }
              MessageToast.show(sMsg);
            }
          },
          postFileToBackEnd: function( Pernr, FileConn, FileConnType, Content) {
      debugger;
       var payLoad = {
                "ImPernr": "00000123",
                "ImFilenameConn": FileConn,
                "ImMimeTypeConn": FileConnType,
                "ImMediaRessConn": btoa(Content)
           }
                this.getOwnerComponent().getModel().create("/FileSet()", payLoad, {
              success: function (odata, Response) {
                if (odata !== "" || odata !== undefined) {
                 sap.m.MessageToast.show("Created successfully");
                } else {
                  sap.m.MessageToast.show("New entry not created");
                }
              },
              error: function (cc, vv) {
              }
            });
          },
          handleUploadPress: function (oEvent) {
            var oFileConn = this.getView().byId("Fileconn");
            var oFileBill = this.byId("Filebill");
            var oFile1 = this.byId("Fileconn").getValue();
            var domRef1 = oFileConn.getFocusDomRef();
            var oFile2 = this.byId("Filebill").getValue();
            var domRef2 = oFileBill.getFocusDomRef();
            var oCheck = this.byId("checkbox").getSelected();
            if ((oFile1 == "") && (oFile2 == "") && (oCheck == "")) {
              var Msgv0 = this.getView().getModel("i18n").getResourceBundle().getText("novalue");
              sap.m.MessageToast.show(Msgv0);
              return;
            } else {
      
               oFileConn.insertHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                      name: "SLUG",
                      value: oFileConn.getValue()
                  }));
      
                   oFileConn.insertHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                      name: "po",
                      value: "12234"
                  }));
      
                  oFileConn.insertHeaderParameter(new sap.ui.unified.FileUploaderParameter({
                      name: "x-csrf-token",
                      value: oModel.getSecurityToken()
                  }));
      
                  oFileConn.setSendXHR(true);
      
                  oFileConn.upload();
              var file1 = domRef1.files[0];
              var that = this;
              this.fileConn = file1.name;
              this.fileconnType = file1.type;
              var file2 = domRef2.files[0];
              this.fileBill = file2.name;
              this.fileBType = file2.type;
      
              var reader = new FileReader();
              reader.onload = function (e) {
      Support
      Insert/edit code sample
      
                var vContent = e.currentTarget.result.replace("data:" + file1.type + ";base64,", "");
                //var vContent2 = e.currentTarget.result.replace("data:" + file2.type + ";base64,", "");
                that.postFileToBackEnd("00000123", that.fileConn, that.fileconnType, vContent);
              };
              reader.readAsDataURL(file1);
            }
          }
        });
      });
      Author's profile photo Mohammed Kawuser
      Mohammed Kawuser

      Hi Himanshu,

      Thanks for the content

      I followed your way for media handling

      when i try to upload file i get GET_ENTITY_SET not implemented.(In error log)

      but i have implemented it.

      ERROR%20LOG

      ERROR LOG

       

      and when i execute it says like this.

      FIELD%20SYMBOL%20NOT%20ASSIGNED

       

      please help me with this.

       

      Thanks!

      Author's profile photo Somnath Choudhury
      Somnath Choudhury

      I hope you have resolved it by now , the ?$format=json is not required .

       

      Thanks.

      Author's profile photo Cuong Luc Dinh
      Cuong Luc Dinh

      Hi Himanshu Pensia,

      thanks for your block, I'm also implementing uploading file functionality for a fiori application, I saw pretty many blogs talking about the topic, but I'm wondering why don't you and they talk about the delete_stream method, don't we need to redefine the method and delete the reference?

      Because I don't know where the file is physically stored, but it makes sense to delete those files if we don't need it any more right? Or it is taken care of by SAP itself?

      Thanks,

      Cuong Luc

      Author's profile photo Julius Draxel
      Julius Draxel

      Thank you for this tutorial. I loosely followed it to implement Media Handling with SAP Mobile Development Kit and it worked almost flawlessly. Only issue I had is that when I used a different table column for the primary key, which was an ID, and setting this as the content type, it wouldn't work. So in Step 4 Line 12

      lo_property = lo_entity->get_property( iv_property_name = 'Filename').

      I replaced

      'Filename'

      with

      'MIMETYPE'

       

      Just as information for anyone having an issue with content type.