Skip to Content
Technical Articles
Author's profile photo lokesh kumar

File Upload and Download in SAP UI5

Hi all,


In this blog post I will explain how to upload and download a text file or image file or xlsx sheet in SAP UI5 Applications.


you should have knowledge about

  • base64
  • file reader
  • blob
  • atob
  • bota


Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

One common application of Base64 encoding on the web is to encode binary data  so it can be included in a data: URL.

In JavaScript there are two functions respectively for decoding and encoding Base64 strings:

atob() Method:-

The atob() method decodes a base-64 encoded string. This method decodes a string of data which has been encoded by the btoa() method.

decodes a Base64-encoded string(“atob” should be read as “ASCII to binary”).

btoa() Method:-

The btoa() method encodes a string in base-64. (“btoa” should be read as “binary to ASCII”).

This method uses the “A-Z”, “a-z”, “0-9”, “+”, “/” and “=” characters to encode the string.



The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data




The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user’s computer, using File or Blob objects to specify the file or data to read.


Event handlers:-



A handler for the error event. This event is triggered each time the reading operation encounter an error.


A handler for the load event. This event is triggered each time the reading operation is successfully completed.



Starts reading the contents of the specified Blob, once finished, the result attribute contains the raw binary data from the file as a string.


Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file’s data.


To Upload a File


We will use FileUploader Control, By using Id we can get the FileUploader object in the controller


View1.view.xml  File


<ui:FileUploader id="fileUploaderFS" multiple="false" />

 <Button text="Upload" type="Accept" press="onUploadFile"/>


View1.controller.js File

when we trigger onUploadFile event in the button it will trigger the function in controller.

//This code is used for uploading documents and images
 var oFileUpload = 

 var domRef = oFileUpload.getFocusDomRef();
 var file = domRef.files[0];
 var that = this;

//This code is used for uploading image or document file

 this.fileName =
 this.fileType = file.type;

  var reader = new FileReader();
           reader.onload = function (e) {
var vContent = e.currentTarget.result
 that.updateFile(that.fileName, that.fileType, vContent);

//This code is used for uploading xlsx sheets

   var oFileUpload = 
  var domRef = oFileUpload.getFocusDomRef();
  var file = domRef.files[0];
  var that = this;
 this.fileName = this.getView().byId("TSFileName")
 this.fileType = file.type;
               var reader = new FileReader();
                 reader.onload = function(e) {
     var data =;
     var workbook =, {
       type: 'binary'

     workbook.SheetNames.forEach(function(sheetName) {
       var XL_row_object = 

    that.json_object = JSON.stringify(XL_row_object);
that.updateFile(that.fileName, that.fileType,


   reader.onerror = function(ex) {




To update the content in backend services

updateFile:function(fileName, fileType, vContent){
            var payLoad={

   var that = this;
   var serviceurl="/sap/opu/odata/sap/ZAPP_EMP1_SRV/";
  var oModel =  
new sap.ui.model.odata.ODataModel(serviceurl); oModel .update("/FILESet('"+payLoad.Filename+"')/$value", 
                 method: "PUT",
                 success: function(data) {"FILE UPDATED SUCCESSFULLY");
                 error: function(e) {


To download file from backend services

       fileName= fileName.toLowerCase()
           var that = this;
           var serviceurl="/sap/opu/odata/sap/servicename_SRV/";
         var oModel =  new sap.ui.model.odata.ODataModel(serviceurl);
          oModel .read("/EntitySet('"+fileName+"')/$value",{
              method: "GET",
              success: function(data,response) {
             var fName=data.Filename
             var fType= data.Filetype;
             var fContent =data.Filecontent;

// If the file is document IS  pdf/msword/plain text

  if(fType==="text/plain" || fType==="application/pdf" 							|| fType==="application/msword" ){
                 fContent =atob(fContent);
  , fName, "txt", fType);
//If the file is excel sheet

 else if(fName.includes(".csv")){
              var  JSONData=fContent;
		Var    ReportTitle =fName;

If JSONData is not an object then JSON.parse will parse the JSON string in an Object
     var arrData = typeof JSONData != 
'object' ? JSON.parse(JSONData) : JSONData;
            var CSV = '';    
            Set Report title in first row or line
            CSV += ReportTitle + '\r\n\n';
            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";
       //2nd loop will extract each column and convert it in
 string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                row.slice(0, row.length - 1);
                //add a line break after each row
                CSV += row + '\r\n';
            if (CSV == '') {        
                alert("Invalid data");
            //Generate a file name
            var fileName = "MyNewReport_";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g,"_");   
            //Initialize file format you want csv or xls
      var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
            // Now the little tricky part.
            // you can use either>>;
            // but this will not work in some browsers
            // or you will not get the correct file extension    
            //this trick will generate a temp <a /> tag
            var link = document.createElement("a");    
            link.href = uri;
 //set the visibility hidden so it will not effect on your web-layout
   = "visibility:hidden";
   = fileName + ".csv";
             //this part will append the anchor tag and remove it after automatic click


//If the file is image

                      fContent =atob(data.Filecontent);
                  var byteNumbers= new Array(fContent.length);
      for (let index = 0; index < fContent.length; index++) {
                  var byteArray= new Uint8Array(byteNumbers)
                  var blob= new Blob([byteArray],{type:fType});
                  var url=URL.createObjectURL(blob)
   "FILE Downloaded Succesfully");
              error: function(e) {



When ever we want to upload or download a file we can use FileUploader control to load the file and we can read the data present in FileUploader Object by using FileReader Object and its methods and get the content present in it . and store it in backend DB. By using atob object we can convert data present in base64 to string format and using File object we can download the file data in specific format.

Assigned Tags

      You must be Logged on to comment or reply to a post.
      Author's profile photo Sagi Yehuday
      Sagi Yehuday

      Add multiple="false" to FileUploader to prevent multiple file selection.


      Author's profile photo lokesh kumar
      lokesh kumar
      Blog Post Author

      thanks for the input.


      with regards

      Lokesh Kumar

      Author's profile photo George Abraham
      George Abraham

      Hi Lokesh,

      Issue: Attachment Upload not working suddenly

      Root Cause: SAP released a latest version of UI5 v1.103.0 on 14th June, 2022 which has a change in the return parameter of the File Uploader component's internal method getFocusDomRef(). Earlier this method used to return the files directly, now it's returning a different format. Hence this issue.

      Fix: We will not be using this internal method getFocusDomRef() now. Instead, can ready the files directly from the event parameters of the "change" event of the FileUploader component.

      You could also use the way suggested in the samples.


      Author's profile photo David Tenkrat
      David Tenkrat

      Thank you, I find this issue today. As hot fix I forced UI5 v1.102 which help but it is just hot fix.

      Author's profile photo Somnath Choudhury
      Somnath Choudhury

      How can I download a text file using RAP and UI annotations . How CDS annotations will be used effectively by means of RAP .Do we have any scenario .We want  avoid the UI specific front end coding . Is this possible .By default FIORI Elements Overview has an excel but in order to achieve Text do we have any .




      Author's profile photo Richie Feeney
      Richie Feeney

      Did you find an answer to this?

      Author's profile photo Somnath Choudhury
      Somnath Choudhury

      there isn't any answer yet . For me the safest best is to go via CDS annotations or SEGW . Though am an ABAP first find a lot flexibility in SAP UI5 libs and JS rather than RAP UI annotations especially for development of  freestyle apps .

      Author's profile photo Chiranjeevi Appapogu
      Chiranjeevi Appapogu

      Hi Lokesh, Thanks for the valid information regarding upload and download in sap ui5.