Skip to Content
Technical Articles
Author's profile photo Bilal Muhammad

Upload/download File in SAP UI5 Application using Gateway

As I was working with functionality for upload and download by following the blog but facing  issues in downloading.I applied a different approach in this blog.Please find below step by step how you can upload and download file.

please note that i am implementing this on Central Hub Gateway  Deployment so will be explaining this in two sections

Section I: Back End

Step-1 : Create Table

First I created a table on back-end system that will contain the uploaded files.you can add many fields you want but  your table must contain Filename,Value and mimetype.

after creating table we developed three Function Modules.

Step-2: Function Modules

Please note all functions are RFC Enabled.

  1. Upload

In this function you will import following parameters and store values in table.

DATA: TEMP_WO LIKE ZBM_WORKORDERAPP-WORKORDER.
  DATA: WA_UPLOAD TYPE ZBM_FILEUPLOAD.

*  SELECT SINGLE WORKORDER INTO TEMP_WO FROM ZBM_WORKORDERAPP
*    WHERE WORKORDER EQ IM_WORKORDER.
*
*  CHECK TEMP_WO IS NOT INITIAL.

  WA_UPLOAD-MANDT = SY-MANDT.
  WA_UPLOAD-WORKORDER = IM_WORKORDER.
  WA_UPLOAD-FILENAME = IM_FILENAME.
  WA_UPLOAD-VALUE = IM_MEDIA_RESOURCE.
  WA_UPLOAD-MIMETYPE = IM_MIME_TYPE.
  WA_UPLOAD-DATESTAMP = SY-DATUM.
  WA_UPLOAD-TIME = SY-UZEIT.

  INSERT INTO ZBM_FILEUPLOAD VALUES WA_UPLOAD.
  IF SY-SUBRC <> 0.
    RAISE DATA_NOT_INSERTED.
  ENDIF.

ENDFUNCTION.

please note this function module is for Create Odata service implementation

2. Get List of files

In my case user can add multiple files for specific workorder. To implement this functionality i created  function module which returns table with file name and file type.

please note this function module is for GetEntitySet Odata service implementation

3. Download

In this function i pass two parameters and get related file.

please note this function module is for GetEntity Odata service implementation

Section II: Front-End SAP Gateway

Step-1: Service Creation

I have created a project in SEGW and an entity type based upload function

following properties were created.

Step-2 : Service Implementation

we will  use mapping

we have implement following services

For Create we used upload function,

for Get Entity we used download

and for Get Entity Set we used Get file names function

thats it !

lets generate.

 

So we have implemented odata service successfully.

Section III: WebIDE

In this section we will see we can use above service in UI5 application

In this Ist we will upload the file to back end system,and the we will download file using UI5 application.

Step-1: Upload file using file uploader.

I will be using file uploader component.

On upload i have implemented  postFiletobackend

we have used JavaScript function btoa for encoding the file content

question arise from where filename,filetype and content come from.below is the code how get details from uploader.

onUpload: function (oEvent) {
var oFileUpload = this.getView().byId("fileUploader");
var domRef = oFileUpload.getFocusDomRef();
var file = domRef.files[0];
var that = this;
this.fileName = file.name;
this.fileType = file.type;
var reader = new FileReader();
reader.onload = function (e) {var vContent = e.currentTarget.result.replace("data:" + file.type + ";base64,", "");
that.postFileToBackend(workorderId, that.fileName, that.fileType, vContent);
};
reader.readAsDataURL(file);
}

once the file uploaded you will get success message

Step-2: Download file

I didn’t use upload collection.Instead of that i have just list down the file related to workorder using list object.

and by using get entity set we will get following view.

Now i have implemented download function on click of row.

I have tried to use sap.ui.core.util.File.save() function but only getting blank or corrupt file.only text file was working fine.

To achieve the goal i have used native JavaScript functionality by creating blob from the file “Value”  and open the blob by using url

Thats it.  Feel free to ask question

Assigned Tags

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

      Hi!

      I followed the tutorial, all its ok to upload, but whe try to download I have the following error at line:

      var fMres = atob(atob(odata.ImMediaResource));

      Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded

      tnks!

      Author's profile photo Bilal Muhammad
      Bilal Muhammad
      Blog Post Author
      Hi Joel,
      Please try following code
       var fMres=atob(odata.ImMediaResource);
                      if(fType===”text/plain”)
                      {
                      sap.ui.core.util.File.save(fMres, fName, “txt”, fType);
                      }
      Also change window.open code with following line
      var ajax=new XMLHttpRequest();
      ajax.open( "GET", url, true);
      ajax.responseType = 'blob';
      hope fully it will work 
      thanks
      Author's profile photo JOEL SANCHEZ
      JOEL SANCHEZ

      Hi Bilal!

      Thanks for your quick response. I made the changes in my function, I don't have errors, but the file doesn't download.

      This is my function:

      onDownload: function (oEvent) {
      //This code was generated by the layout editor.
      var workorder = oEvent.getSource().getBindingContext().getProperty(Workorder);
      var filename = oEvent.getSource().getBindingContext().getProperty(Filename);
      var itemString = "/ZFileSet(ImFilename='" + filename + "',ImWorkorder='" + workorder + "')";
      var oDataModel = this.getOwnerComponent().getModel();
      oDataModel.read(itemString, {
      success: function (odata, response) {
      var fName = odata.ImFilename;
      var fType = odata.ImMimeType;
      //var fMres = atob(atob(odata.ImMediaResource));
      var fMres = atob(odata.ImMediaResource);
      if (fType === "text/plain") {
      //sap.ui.core.util.File.save(fMres, fName.replace(".txt", ""), "txt", fType, "utf-8, true");
      sap.ui.core.util.File.save(fMres, fName, "txt", fType);
      } else {
      var byteNumbers = new Array(fMres.length);
      for (var i = 0; i < fMres.length; i++) {
      byteNumbers[i] = fMres.charCodeAt(i);
      }
      var byteArray = new Uint8Array(byteNumbers);
      var blob = new Blob([byteArray], {
      type: fType
      });
      var url = URL.createObjectURL(blob);
      //window.open(url, '_blank');
      var ajax = new XMLHttpRequest();
      ajax.open("GET", url, true);
      ajax.responseType = 'blob';
      }
      },
      error: function (oError) {}
      });
      }
      what can be the error?
      Tnks!
      Author's profile photo Michael Smith
      Michael Smith

      Bilal Muhammad , just out of curiosity - why is it necessary to use the btoa function after already encoding the file as base64 with readAsDataURL?

      Author's profile photo Michael Christa
      Michael Christa

      I agree with Michael. It is not necessary to use btoa function to download the file. If you use UploadCollection, the code becomes quite simple. E.g. Downloading of files can be achieved with 5 lines of code.

      var sServiceUrl = this.sServiceUrl + "/DocumentSet('1234')/$value";
      var oUplColItem = new UploadCollectionItem();
      oUplColItem.setUrl(sServiceUrl);
      oUplColItem.setMimeType("application/pdf");
      oUplColItem.download(false);