Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
former_member184739
Contributor

Dear All,

This blog will walk you through step-by-step to upload files from an HTML5 webapp.

Here is the short overview of what technologies we are going to use to successfully load a binary file from a client machine to a remote SAP server.

HTML5 File reader : The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer. We use readAsArrayBuffer method to read the contents of a specified Blob or File.

Jquery AJAX:To exchange data to and from server, and updating parts of a web page - without reloading the whole page.

Putting much simpler, AJAX is to load data in the background(asynchronous) and display it on the webpage.

HTML5 progress bar: To track real time progress when file is getting uploaded...

Gateway media links: The OData Channel from gateway provides us the interface to receive binary data from the front end and then

stored it in an SAP Business Suite backend system whatever applies.

Enough theory.Lets get started...

<!DOCTYPE html>

<html>

  <head>

  <script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" > </script>

    <script type="text/javascript">

    var token1 = '';

    var xhr = new window.XMLHttpRequest();

    var file = " ";

    function upload() {

         file = document.getElementById('attafh').files[0];

        if (file) {

            UploadMe(file);

        }

    }

    function UploadMe(readFile) {

        var reader = new FileReader();

        reader.readAsArrayBuffer(readFile); //array buffer

        reader.onload = loaded;

//         reader.onerror = errorHandler;

    }

    function loaded(evt) {

        var fileString = evt.target.result;                  

          ///**** Save Personal Details & Questions & Files *****/

         // Begin of Get X-CSRFT token

             $.ajax({

                 url: 'https://test.com:8080/sap/inv/opu/odata/sap/Z_GET_ATTACHMENTS_SRV/$metadata',

                 type: "GET",

                 contentType: "application/atom+xml;type\x3dentry;",

                 dataType: "",

                 headers: {

                     "x-csrf-token": "fetch",

                     Authorization: "Basic ZDDDDDDDDD="

                 },

             success: function (data, textStatus, request) {

             token1 = request.getResponseHeader('x-csrf-token');

    

    

                 $.ajax({       

                  type: 'POST',

                  url: "https://test.com:8080/sap/inv/opu/odata/sap/Z_GET_ATTACHMENTS_SRV/Documents/",                   

                   xhr: function()

                 {           

                    //Upload progress

                     xhr.upload.addEventListener("progress", function(evt){

                      if (evt.lengthComputable) {

                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);

                     $('.progress').val(percentComplete);

                       //Do something with upload progress

                       console.log(percentComplete);

                      }

                    }, false);

                             

                  xhr.addEventListener("error", function(evt){

                alert("There was an error attempting to upload the file.");

                return;

                    }, false);

         

                    return xhr;

                 },

        

                contentType: "application/json",

                processData: false,                   

                data: fileString,

                dataType: "text",

                headers: {

                          "x-csrf-token" : token1,

                          "Authorization" : "Basic ZDDDDDDDDDD",

                          "slug": file.name + "|" + file.type + "|" + file.size + "|"

                },

                success: function(data){

                   alert("File uploaded successfully");

                  }

                });

           

                  }

             });

    };

    function abortRead() {

    xhr.abort();

    $('.progress').val(0);

      }

    </script>

  </head>

  <body>

    <input type="file" id="attafh"  class="AlltextAccount"  />

      <input type="button" value="upload" onclick="upload()" />

      <button onclick="abortRead();">Cancel</button>

      <progress class="progress" value="0" max="100"> </progress>

  </body>

</html>

What above code does is, we had a file placed in the Body and when choose file and upload, we extracted the contents using File reader.

For sending this to SAP gateway, we need X-CSRF-Token to make any modifications request. Please note the AJAX heaeders when making POST request.

"ProcessData" has to be set false. Also parameter "Slug" can be used to send file name, type and size. Later this can be split in the server using "SPLIT" statement.

For tracking progress in real time we make of this event. xhr.upload.addEventListener("progress", function(evt).

We can custom tailor the progress bar theme too...

HTML:

   <progress class="progress" value="0" max="100" class="html5">

  </progress>

CSS:

progress[value] {

  -webkit-appearance: none;

   appearance: none;

  width: 150px;

  height: 22px;

  padding-top: 5px;

  display:none

}

progress[value]::-webkit-progress-bar {

  background-color: #eee;

  border-radius: 2px;

  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.25) inset;

}

progress[value]::-webkit-progress-value {

background-image:

  -webkit-linear-gradient( 135deg,

  transparent,

  transparent 33%,

  rgba(0,0,0,.1) 33%,

  rgba(0,0,0,.1) 66%,

  transparent 66%),

    -webkit-linear-gradient( top,

  rgba(255, 255, 255, .25),

  rgba(0,0,0,.2)),

     -webkit-linear-gradient( left, #09c, #690);

     border-radius: 2px;

    background-size: 35px 20px, 100% 100%, 100% 100%;

}

Result:

You can check below link to know more on this.

http://css-tricks.com/html5-progress-element/

http://lea.verou.me/polyfills/progress/

Coming to server side we just needd to create an Entity type with "Media" flag set. And implement the steps covered in these blogs.

How To Upload and Download Files Using SAP NW Gateway SP06

scn.sap.com/community/netweaver-gateway/blog/2013/02/22/how-to-read-photo-from-sap-system-using-sap-netweaver-gateway

Thanks to the above blogs for their valuable contributions.

Code :

method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_STREAM.

  FIELD-SYMBOLS:<FS_DOC> TYPE ZUPLOAD_DOC.

  Data:ls_doc type ZUPLOAD_DOC,

       lt_file_info type table of string,

       ls_file_info like line of lt_file_info,

       ls_result type ZBAPIRETURN,

       lv_file_info type string.

  Data:

       lv_file_name type /GC1/DTE_MSG_TXT,

       lv_file_type type /GC1/DTE_MSG_TXT,

       lv_file_length type string,

       lv_index type sy-tabix.

  data: lt_doc type table of ZUPLOAD_DOC.

  CREATE DATA ER_ENTITY TYPE ZUPLOAD_DOC.

  ASSIGN:ER_ENTITY->* TO <FS_DOC>.

//File name and other arguements will be received here..

  lv_file_info = iv_slug.

  split lv_file_info at '|' into table lt_file_info.

  IF sy-subrc eq 0.

    LOOP AT lt_file_info into ls_file_info.

      lv_index = sy-tabix.

      CASE  lv_index.

        WHEN 1.

          lv_applid = ls_file_info.

        WHEN 2.

          lv_file_name = ls_file_info.

        WHEN 3.

          lv_file_type = ls_file_info.

        WHEN 4.

          lv_file_length = ls_file_info.

        WHEN 5.

      ENDCASE.

      clear:ls_file_info,lv_index.

    ENDLOOP.

    ls_doc-FNAME = lv_file_name.

    ls_doc-FTYPE = lv_file_type.

    ls_doc-FLENGTH = lv_file_length.

    ls_doc-fcontent = is_media_resource-value."File content will be here.

   append ls_doc to lt_doc[].

        <FS_DOC> = ls_doc.

    endif.

  ENDIF.

endmethod.

Result after reaching server:

File received successfully.

The above logic can handle filesof type .doc, .docx, .pdf, .png, .jpg, .xls, .xlsx.

Please note that this functionality only in modern browsers which supports HTML5 - File API.

I am planning to do a writeup on handling legacy browsers IE9 and below too and also to handle multiple files as well.

Please share your feedback and welcome your corrections to improve this content.

Cheers

Prabaharan

5 Comments
Labels in this area