Skip to Content

Hello World!

I started my journey into SAPUI 5 four months ago at BMB Services as an intern as part of completing my Master programme at ESIEE Paris, and it has been for the most part, a consuming love affair.

For me staying focused was important, like a baby to modern day gadgets, I seem to find out that you get your head spinning on the varous interesting careers that the SAP ecosystem proposes,  but remaining true to my love of the web kept me steadfast and pushed me thus far.

While building a sentimental analysis application based on SAP HANA using SAPUI5, I recently had to scan through a lot of blog posts to understand the workings. For the Fileupload, this was not a feature I had immediately envisaged and wondered why I never saw it coming before my boss added this wonderful request. In truth, I got totally seperated, not knowing how SAPUI5 would implement such a simple feature.Maybe I expected a very diffcult task ahead. Being pressed with time and wanting to quickly implement a working feature, I had several discussions, perfomed documentation reads and rereads, and guess what, I was getting no where with all that hurry.

I must say that learning to learn is something. Through this period, I have taken a back seat to watch and understand my learning patterns. It turns out that I could spend a heck lot of time looking for solutions on the internet, circling around the same thing and the at same time circling further away from the solution of the task at hand. This is crazy, time spent can be enourmous especially relative to the accomplished tasked. But accodring to  Sir Isaac Newton, If I have seen further than others, it is by standing upon the shoulders of giants, hence , thanks SCN.

I think on the average, I spent more time on Fileuploader than I did understanding any other feature of SAP UI5- the reason, obvious, but for me, it was lesson learnt!

So here I put together snippets of code for end to end  upload and database save/store to  database retrieve  to display your file on your page. In my case, the files were Images, I am sure you can be extended for other file types. Investigate.

This post requires that you have some prequisite knowledge of MVC  and SplitApp approaches in SAPUI5.


Enjoy:)

MVC UPLOAD FRONT END VIEW XML

<u:FileUploader      

id="FileLoader"       width="100%"       tooltip="Upload picture of contact"       uploadComplete="handleUploadComplete"       change="handleValueChange"       typeMissmatch="handleTypeMissmatch"       style="Emphasized"       fileType="jpeg,jpg,png"       placeholder="Choose a file for Upload...">        </u:FileUploader>    <Button      text="Upload File"      press="handleUploadPress"/>

                                    

MVC UPLOAD FRONT END CONTROLLER  JS

handleUploadPress : function(oEvent) 
  { 
       var fileLoader =this.getView().byId("FileLoader");//XML View

            var fileName = fileLoader.getValue(); 
            jQuery.sap.require("sap.ui.commons.MessageBox"); 
              if (fileName == "" ) 
                { 
                        sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information"); 
              } 
              else 
              { 
                        var uploadUrl = "services/PictureFileUpload.xsjs?file_name="+fileName; 
                        var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
                        var form = $(formEle).find("form")[0] ; 
                        var fd = new FormData(form);    
                        $.ajax({ 
                                  url: uploadUrl, 
                                  type: "GET", 
                                  beforeSend: function(xhr) 
                                  { 
                                            xhr.setRequestHeader("X-CSRF-Token", "Fetch"); 
                                  }, 
                                  success: function(data, textStatus, XMLHttpRequest) { 
                                            var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token'); 
                                            $.ajax({ 
                                                      url: uploadUrl, 
                                                      type: "POST", 
                                                      processData :false , 
                                                      contentType: false , 
                                                      data:fd, 
                                                      beforeSend: function(xhr) 
                                                      { 
                                                                xhr.setRequestHeader("X-CSRF-Token", token); 
                                                      }, 
                                                      success: function(data, textStatus, XMLHttpRequest)  
                                                      { 

                                                           var resptext = XMLHttpRequest.responseText; 
                                                           jQuery.sap.require("sap.ui.commons.MessageBox"); 
                                                           sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information"); 


                                                          if(data == "Upload successful"){
                                                             sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information"); 

                                                          }


                                                      }, 
                                                      error: function(data, textStatus, XMLHttpRequest) 
                                                      { 
                                                                sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error"); 
                                                      } 
                                            }); 
                                  }} ) ; 
              } 
  },
 

.XSJS UPLOAD SERVICE  SERVER SIDE

Create your schema table with a column of type BLOB

$.response.contentType = "text/html"; 
var ID  = $.request.parameters.get("ID");
try 
 { 
           var conn = $.db.getConnection(); 
           var filename = $.request.parameters.get("file_name"); 
           var pstmt = conn.prepareStatement( "UPDATE \"SCHEMA\".\"MYTABLE\" SET IMAGE_CONTENT = ? where ID='"+ID+"'");
           if($.request.entities.length>0){ 
                          var file_body = $.request.entities[0].body.asArrayBuffer(); 
                          pstmt.setBlob(1,file_body);
                                pstmt.execute();
                                $.response.setBody("[200]:Upload successful!"); 
           } 
           else 
           { 
                     $.response.setBody("No Entries"); 
           } 
           pstmt.close(); 
           conn.commit(); 
           conn.close(); 

 } 
 catch(err) 
 { 
           if (pstmt !== null) 
           { 
                     pstmt.close(); 
           } 
           if (conn !== null) 
           { 
                     conn.close(); 
           } 
           $.response.setBody(err.message); 
 }  
 

That saves you file in to the database

RETRIEVING SAVED PICTURE



MVC UPLOAD FRONT END VIEW XML

                        <Image id="profileImg" class="primeImg" src="data:image/jpeg;base64,' + hexToBase64({IMAGE_CONTENT})"           width="{/imageWidth}" >                              <layoutData>                                <FlexItemData growFactor="1" />                              </layoutData>                         </Image>

MVC UPLOAD FRONT END CONTROLLER  JS


You can choose to trigger this fuction any way you choose, in my case , the image were to be shown the user clicked on a detail table master row which navigates to open a new contact page.


Things to note

     handleLineItemPress : function (evt) {


          var context = evt.getSource().getBindingContext();
          var ID = context.getObject().ID;



          var xmlHTTP = new XMLHttpRequest();

        xmlHTTP.open('GET', 'services/GetImage.xsjs?id=' +ID, true);
        xmlHTTP.responseType = 'arraybuffer';

        xmlHTTP.onload = function(e) {

             if (this.status == 200) {
                  var arr = new Uint8Array(this.response);
                  var raw = String.fromCharCode.apply(null, arr);
                  var b64 = btoa(raw);
                  var dataURL = "data:image/jpeg;base64," + b64;
                  document.getElementById("ProfileEdit--profileImg").src = dataURL;

                 //document.getElementById('errorMessage').innerHTML = '';
               }
             else if (this.status == 404) {
                  //document.getElementById('errorMessage').innerHTML = 'Image not found';
                  document.getElementById("ProfileEdit--profileImg").src = 'img/no_user.png';
               }
             else{
                  document.getElementById("ProfileEdit--profileImg").src = 'img/no_user.png';
             }

        };

        xmlHTTP.send();

          //after image is set
        this.nav.to("ProfileEdit", context);
     },



.XSJS RETRIEVE SERVICE  SERVER SIDE


var schema_name = "YOUR_SCHEMA_NAME";
var id = $.request.parameters.get('id');
var conn = $.db.getConnection();

try {
    var query = "Select IMAGE_CONTENT From \"SYSTEM\".\"BMBFRIENDS\" Where ID = '" + id + "'";

    var pstmt = conn.prepareStatement(query);
    var rs = pstmt.executeQuery();
    if(rs.next()){
        $.response.headers.set("Content-Disposition", "Content-Disposition: attachment; filename=filename.jpg");
        $.response.contentType = 'image/jpg';
        $.response.setBody(rs.getBlob(1));
        $.response.status = $.net.http.OK;
    }
    else{
         $.response.contentType = 'text/html';
        $.response.setBody("Image not found");
        $.response.status = 404;
    }

} catch (e) {
    $.response.setBody("Error while downloading : " + e);
    $.response.status = 500;
}
conn.close();



OK thats it! C’est tout!


I hope I have save you some eyelashes,  be linient, its my first post, but you can go all the way to positive criticisms, we all love lets get your sentiments too 🙂


Thanks



To report this post you need to login first.

3 Comments

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

  1. Lars Breddemann

    Hey John,

    nice blogging! That’s exactly the kind of writing I am hoping to read here on SCN.

    It’s personal, it tells of your own experience and it’s written in an engaging way.

    Although you definitively want to work on quality control (spelling, formatting, you know the usual suspects) of your writing, I like this far better than the streamlined “this is how you do xyz”-blog posts that only seem to serve the author’s reputation.

    Thanks for this and keep on writing. More and more.

    – Lars

    (0) 
  2. Angelica Peñas

    Hi John,

    Nice blog! but I need some help on my service, this statement “$.request.entities.length>0” is not satisfied, it seems that it has no entries 🙁 Can you help me? Thanks!

    Regards,

    Jeka

    (0) 

Leave a Reply