There are no secrets to success. It is the result of preparation, hard work, and learning from failure.

Saturday 10 November 2018

Base64 conversion of selected file in SAPUI5

Click here and follow my SAP UI5/FIORI snippets and information Page
I have made example of base64 conversion of any selected file,below I have shown Application Structure,View Part,Controller Part and Result.Go through it and please let me know in case of any issue/doubt.

Application Structure 
View Part
<mvc:View controllerName="Base64.controller.S1" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
xmlns="sap.m" xmlns:u="sap.ui.unified" xmlns:l="sap.ui.layout">
<App id="idAppControl">
<pages>
<Page title="{i18n>title}">
<content>
<l:VerticalLayout>
<u:FileUploader name="myFileUpload" tooltip="Upload your file to the local server" change="handleSelectFile"/>
</l:VerticalLayout>
</content>
</Page>
</pages>
</App>
</mvc:View>

Controller Part
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("Base64.controller.S1", {
      
      // When user select the file then this method will call....
handleSelectFile: function (oEvent) {
var fileDetails = oEvent.getParameters("file").files[0];
sap.ui.getCore().fileUploadArr = [];
if (fileDetails) {
var mimeDet = fileDetails.type,
fileName = fileDetails.name;
// Calling method....
this.base64coonversionMethod(mimeDet, fileName, fileDetails, "001");
} else {
sap.ui.getCore().fileUploadArr = [];
}
},

// Base64 conversion of selected file(Called method)....
base64coonversionMethod: function (fileMime, fileName, fileDetails, DocNum) {
var that = this;
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function (fileData) {
var binary = "";
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
that.base64ConversionRes = btoa(binary);
sap.ui.getCore().fileUploadArr.push({
"DocumentType": DocNum,
"MimeType": fileMime,
"FileName": fileName,
"Content": that.base64ConversionRes,
});
};
reader.readAsArrayBuffer(fileData);
};
}
var reader = new FileReader();
reader.onload = function (readerEvt) {
var binaryString = readerEvt.target.result;
that.base64ConversionRes = btoa(binaryString);
sap.ui.getCore().fileUploadArr.push({
"DocumentType": DocNum,
"MimeType": fileMime,
"FileName": fileName,
"Content": that.base64ConversionRes,

});
};
reader.readAsBinaryString(fileDetails);
},
});
});
Result
See the property name 'Content' in console(developer tool),That is the Base64 converted string.


No comments:

Post a Comment