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:
- A trial account on SAP Cloud Platform with Web IDE Service enabled.
- Destination to On premises system is maintained in the SAP Cloud Platform
- Hana Cloud Connector should be in active state.
- 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.
- Active security session management.
- Currently, URLs containing segment parameters such as; mo ;o, or ;v=.. Cannot be processed in the soft-state processing mode.
Step-by-Step Procedure:
- Creating the Odata Service.
- Register the Odata Service and test it from Gateway.
- Consume the Odata Service in UI5 Application.
STEP 1: Creating the Odata Service
- Create Table in SE11. (You may put any name as you like, i have used name ZFILE for the Table).
- Goto SEGW, Create OData project, import your table (ZFILE) from DDIC structure to create ENTITY_TYPE.
- Select the entity type “ZFILE” you just created and Choose the check box media as selected.
- 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.
- 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.
- 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.
- 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.
- 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
- Register the Odata service to the Gateway server.
- Open the Odata service with SAP Gateway Client.
- 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.
- 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.
- Go to SAP Web IDE, and create a new project with UI5 application template.(assuming that name of view and controller is VIEW1)
- 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>
- 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() { } }); }, }); });
Nice one Himanshu. Thanks for sharing.
Nice one,
I am getting 405 method not allowed error.
Thanks,
Venkatesh.
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
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?
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.
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
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:
needs to become
in order for it to work
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?
Excellent post, good work Himanshu??
Hi Himanshu,
Can i use this '/$value' in Odata V2 Model?
Yes Avinash,
You can use ‘/$value’ in Odata V2 Model.
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
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?
Hi,
In my CREATE_STREAM method the IV_SLUG parameter is always empty.
Could you please help me?
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 LOG
and when i execute it says like this.
please help me with this.
Thanks!
I hope you have resolved it by now , the ?$format=json is not required .
Thanks.
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
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
I replaced
with
Just as information for anyone having an issue with content type.