Skip to Content

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() {
    
    
                    }
                });
    
            },
    
        });
    });​

 

To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

    1. Himanshu Pensia 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

       

      (0) 
  1. 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

     

     

     

    (0) 

Leave a Reply