File upload using SAPUI5 Control
Below is the approach that I tried and successfully able to upload File to the Gateway Service.
Step1: Extend FileUploader (sap.ui.unified.FileUploader)
Overwrite the Upload method by AJAX call passing X-CSRF-Token
jQuery.sap.declare(“com.ODataFileUploader.Component”);
jQuery.sap.require(“sap.ui.unified.FileUploader”);
sap.ui.unified.FileUploader.extend(“com.ODataFileUploader.Component”, {
metadata : {
properties : {
“modelName” : “string”,
“slug” : “string”,
“csrf” : “string”
}
},
upload : function() {
var file = jQuery.sap.domById(this.getId() + “-fu”).files[0];
try {
if (file) {
this._bUploading = true;
var that = this;
var _handleSuccess = function(data, textStatus, jqXHR){
that.fireUploadComplete({“response”: “Success: File uploaded to entity” });
that._bUploading = false;
};
var _handleError = function(data){
var errorMsg = ”;
if (data.responseText[1]){
errorMsg = /<message>(.*?)<\/message>/.exec(data.responseText)[1];
}else{
errorMsg = ‘Something bad happened’;
}
that.fireUploadComplete({“response”: “Error: ” + errorMsg});
that._bUploading = false;
};
var oHeaders = {
“x-csrf-token”: this.mProperties.csrf,
“slug”: this.mProperties.slug,
“X-Requested-With”: “XMLHttpRequest”,
“Content-Type”: file.type,
“DataServiceVersion”: “2.0”,
“Accept” : “text/plain, */*”
};
jQuery.ajax({
type: ‘POST’,
url: this.getUploadUrl(),
headers: oHeaders,
cache: false,
contentType: file.type,
dataType: “text”,
processData: false,
data: file,
success: _handleSuccess,
error: _handleError
});
jQuery.sap.log.info(“File uploading to ” + this.getUploadUrl());
}
} catch(oException) {
jQuery.sap.log.error(“File upload failed:\n” + oException.message);
}
},
renderer : {
}
});
Step2: Fetch X-CSRF-Token
var url1 = getUrl(“/sap/opu/odata/sap/ZGW_FILES_APP_SRV”);
var csrfToken = “”;
var aData = jQuery.ajax({
url : url1,
headers: { “X-CSRF-Token”:”Fetch” ,
“X-Requested-With”: “XMLHttpRequest”,
“DataServiceVersion”: “2.0” },
type: “GET”,
contentType : “application/json”,
dataType : ‘json’,
success : function(data, textStatus, jqXHR) {
csrfToken = jqXHR.getResponseHeader(‘x-csrf-token’);
oFileUploader1.setCsrf(csrfToken);
oFileUploader1.setSlug(“200000664_MOB15”);
oFileUploader1.setUploadUrl(getUrl(“/sap/opu/odata/sap/ZGW_FILES_APP_SRV/FileSet”));
oFileUploader1.upload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
});
Step3: Call File Upload Service by passing already Fetched X-CSRF-Token along with any inputs in the HTTP Headers
Step4: Upload the Actual file on Screen
From Desktop:
From Mobile:
Step5: Trigger Upload Action
var btnSubmit = new sap.m.Button({
text:‘Trigger Upload’,
press:function() {
var url1 = getUrl(“/sap/opu/odata/sap/ZGW_FILES_APP_SRV”);
var csrfToken = “”;
var aData = jQuery.ajax({
url : url1,
headers: { “X-CSRF-Token”:“Fetch” ,
“X-Requested-With”: “XMLHttpRequest”,
“Content-Type”: “image/jpeg”,
“DataServiceVersion”: “2.0” },
type: “GET”,
//jsonpCallback : ‘getJSON’,
contentType : “application/json”,
dataType : ‘json’,
//data : “”,
success : function(data, textStatus, jqXHR) {
csrfToken = jqXHR.getResponseHeader(‘x-csrf-token’);
oFileUploader1.setCsrf(csrfToken);
oFileUploader1.setSlug(“2000006”);
oFileUploader1.setUploadUrl(getUrl(“/sap/opu/odata/sap/ZGW_FILES_APP_SRV/FileSet”));
oFileUploader1.upload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
});
Hi Jenish, it is a very helpful blog. I am working on file uploader functionality. I have created gateway service which upload files through GOS. Now in UI5 I am getting csrf token thru ajax call. I am stuck with file uploader extend, this extension must be done where?? can you please guide me with this.
Best regards,
Siva
Hi Sivadurga,
You can have that declared in separate FileUploader.js file and refer it.
Jenish, thanks for your reply, I have extended this API in index.html under <script> tag. Its working fine, i am able to upload files from FIORI App to SAP.
Best regards,
Siva
Wonderful 🙂
Hi Jenish,
Thanks for your post.It helped me to upload the file to gateway server successfully.
You have used the sap.ui.unified.FileUploader to upload the files.
It would be of great help if you let me know the end to end process of how file upload can be achieved using sap.m.UploadCollection.i.e. from SAPUI5 application to abap server using gateway services.
In sap.m.UploadCollection we have option to upload multiple files. I want to know, how it is handled in gateway services.
Thanks and Regards,
Sagar M Patil
Hi.
Do you have any useful links for the same?
Hello Prabhat,
I have a similar requirement. I need to upload multiple attachments which can be of different types. I want to do this via UploadCollection and finally send the group of attachments to abap server as a gateway service.
Were you able to achieve this.
Any help in this regard is appreciated
Kind Regards,
Faiza.
Hi Faiza,
Yes I was able to do file upload using Upload Collection.
I didn't use 'pending' feature though.
I checked your profile, if you have sap ID, then we can discuss over skype call.
Else I will try to explain things here.
Regards,
Prabhat.Singh.Pathania
Hello Sagar,
I have a similar requirement. I need to upload multiple attachments which can be of different types. I want to do this via UploadCollection and finally send the group of attachments to abap server as a gateway service.
Were you able to achieve this.
Any help in this regard is appreciated
Kind Regards,
Faiza.
Hello Faiza,
I have implemented it as below, i am not sure but might work for you, also i have attach a link below that might help you to understand the backend part as well.
//In XML :
<UploadCollection change="onAttachmentChange"
fileDeleted="onAttachmentDeleted" fileRenamed="onAttachmentRenamed"
fileSizeExceed="onAttachmentSizeExceeded"
fileType="{detailView>/allowedFileExtension}"
id="idAttachments" maximumFilenameLength="255"
multiple="false" noDataText="No attachment found"
showSeparators="All" typeMissmatch="onAttachmentTypeMissmatched"
uploadComplete="onAttachmentUploadComplete"
uploadEnabled="true" uploadUrl="{detailView>/attachmentUploadURL}">
< UploadCollectionItem contributor="{CreatedBy}"
documentId="{Itemno}" enableDelete="true"
enableEdit="false" fileName="{Filename}"
id=" idAttachmentItem " mimeType="{Mimetype}"
uploadedDate="{ path: 'CreatedOn', type: 'sap.ui.model.type.Date', formatOptions: {pattern: 'dd.MM.yyyy'} }"
url="{Url}" visibleDelete="{app>/requestEditMode}"
visibleEdit="false" />
</UploadCollection>
//Controller file:
//On Init :
this._oAttachments = this.byId("idAttachments");
this._oAttachmentItem = this.byId("idAttachmentItem").clone();
this._oComponent = this.getOwnerComponent();
this._oModel = this._oComponent.getModel();
this._oSecurityToken = null;
this._oViewProperties = new JSONModel({
busy: false,
delay: 0,
allowedFileExtension: ["jpg", "png", "bmp", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "msg"],
attachmentUploadURL: ""
});
this.setModel(oViewModel, "detailView");
//While binding the view, bind attachment also by calling below method:
_bindAttachments: function(sObjectPath) {
var sBindingPath = sObjectPath + "/Attachments";
this._oAttachments.bindAggregation("items", {
path: sBindingPath,
template: this._oAttachmentItem,
templateShareable: true
});
//update upload url for control
var _sUploadURL = window.location.origin + (this._oModel.sServiceUrl + sObjectPath) + "/Attachments";
this._oViewProperties.setProperty("/attachmentUploadURL", _sUploadURL);
}
// to get xcsrf token, call below function once view is binded, which might used below
this._oModel.refreshSecurityToken(jQuery.proxy(this._getSecToken, this));
_getSecToken: function(oData, oResponse) {
this._oSecurityToken = oResponse.headers['x-csrf-token'];
},
//UploadCollection events :
onAttachmentChange: function(oEvent) {
var sFileName = "";
var aFiles = oEvent.getParameter("files");
for (var i = 0; i < aFiles.length; i++) {
sFileName = aFiles[i].name;
break;
}
var oCustomerHeaderSlug = new sap.m.UploadCollectionParameter({
name: "slug",
value: sFileName
});
oEvent.getSource().addHeaderParameter(oCustomerHeaderSlug);
// Header Token
var oCustomerHeaderToken = new sap.m.UploadCollectionParameter({
name: "x-csrf-token",
value: this._oSecurityToken
});
this._oAttachments.addHeaderParameter(oCustomerHeaderToken);
},
onAttachmentDeleted: function(oEvent) {
var sDeletePath = oEvent.getParameter("item").getBindingContext().sPath;
// logic to implement remove attachment
//i.e use this._oModel.remove() function by passing above path.
},
onAttachmentRenamed: function(oEvent) {
// do as per need
},
onAttachmentSizeExceeded: function() {
// do as per need
},
onAttachmentTypeMissmatched: function() {
// can be shown message for mismatch
},
onAttachmentUploadComplete: function(oEvent) {
// just refresh the attachment with updated data
var oItemsBinding = this._oAttachments.getBinding("items");
oItemsBinding.refresh();
}
Thats all !! 🙂
http://scn.sap.com/community/developer-center/front-end/blog/2016/03/29/using-the-uploadcollection-to-uploaddownload-archivelink-files-via-gateway
Regards,
Akhilesh
Hello Akhilesh,
I tried this approach but not able to make UploadCollection work.
I have posted a question on SDN, refer to link: LINK
Can you provide some insight if possible.
Regards,
Harish
Hi Faiza,
I am able to upload multiple files using file upload collection. I am using FileReader java script object inside onChange() event of uploadCollection control ot get the file details.
Regards,
Sagar M Patil
Hello Sagar,
Could you please kindly provide some spinet code for upload the multiple file as you have already did.
Thanks a lot in advance .
Peeyush
Hi Jenish,
Brilliant blog ..
Could you please share your code base via JSBin or else?
One question, why did you used this approach of overriding the existing method? FileUploader.upload()? Just wish to know the reason behind the need of extension, what was your use case? where did you got struck?
Please explain and share the code.
Thanks
Chet
Hi Jenish sir,
I am new to SAPUI5 i dont know how to use sap netweaver gateway image services in sapui5.I tried below code in single html page using eclipse but i am getting some errors please correct it revert back to me
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m, sap.ui.unified"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->
<script>
sap.ui.localResources("csrf_image");
var app = new sap.m.App({initialPage:"idApp1"});
var page = sap.ui.view({id:"idApp1", viewName:"csrf_image.App", type:sap.ui.core.mvc.ViewType.JS});
app.addPage(page);
app.placeAt("content");
</script>
<script>
jQuery.sap.declare("com.ODataFileUploader.Component");
jQuery.sap.require("sap.ui.unified.FileUploader");
sap.ui.unified.FileUploader.extend("com.ODataFileUploader.Component", {
metadata : {
properties : {
"modelName" : "string",
"slug" : "string",
"csrf" : "string"
}
},
upload : function() {
var file = jQuery.sap.domById(this.getId() + "-fu").files[0];
try {
if (file) {
this._bUploading = true;
var that = this;
var _handleSuccess = function(data, textStatus, jqXHR){
that.fireUploadComplete({"response": "Success: File uploaded to entity" });
that._bUploading = false;
};// end
var _handleError = function(data){
var errorMsg = '';
if (data.responseText[1]){
errorMsg = /<message>(.*?)<\/message>/.exec(data.responseText)[1];
}else{
errorMsg = 'Something bad happened';
}
that.fireUploadComplete({"response": "Error: " + errorMsg});
that._bUploading = false;
}; // end of handleerror
var oHeaders = {
"x-csrf-token": this.mProperties.csrf,
"slug": this.mProperties.slug,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": file.type,
"DataServiceVersion": "2.0",
"Accept" : "text/plain, */*"
};
jQuery.ajax({
type: 'POST',
url: this.getUploadUrl(),
headers: oHeaders,
cache: false,
contentType: file.type,
dataType: "text",
processData: false,
data: file,
success: _handleSuccess,
error: _handleError
});
jQuery.sap.log.info("File uploading to" + this.getUploadUrl());
} // end of if file
} catch(oException) {
jQuery.sap.log.error("File upload failed:\n" + oException.message);
}
},
renderer : {
}
});
//end of upload function
//csrf token fetch
var oFileUploader = new sap.ui.unified.FileUploader({
id : "file1",
src:"{Pfilename}",
uploadUrl:"upload/",
});
var url1 = "sap/opu/odata/SAP/ZPROJECT_SHOPPING_CART_SRV";
var csrfToken = "";
var aData = jQuery.ajax({
url : url1,
headers: { "X-CSRF-Token":"Fetch" ,
"X-Requested-With": "XMLHttpRequest",
"DataServiceVersion": "2.0" },
type: "GET",
contentType : "application/json",
dataType : 'json',
success : function(data, textStatus, jqXHR) {
csrfToken = jqXHR.getResponseHeader('x-csrf-token');
oFileUploader1.setCsrf(csrfToken);
oFileUploader1.setSlug("200000664_MOB15");
oFileUploader1.setUploadUrl(getUrl("sap/opu/odata/SAP/ZPROJECT_SHOPPING_CART_SRV/ProductimageSet"));
oFileUploader1.upload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
var btnSubmit = new sap.m.Button("file2",{
text:'Trigger Upload',
press:function() {
var url1 = getUrl("/sap/opu/odata/SAP/ZPROJECT_SHOPPING_CART_SRV/");
var csrfToken = "";
var aData = jQuery.ajax({
url : url1,
headers: { "X-CSRF-Token":"Fetch" ,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "image/jpeg",
"DataServiceVersion": "2.0" },
type: "GET",
//jsonpCallback : ‘getJSON’,
contentType : "application/json",
dataType : 'json',
//data : “”,
success : function(data, textStatus, jqXHR) {
csrfToken = jqXHR.getResponseHeader('x-csrf-token');
oFileUploader1.setCsrf(csrfToken);
oFileUploader1.setSlug("2000006");
oFileUploader1.setUploadUrl(getUrl("/sap/opu/odata/SAP/ZPROJECT_SHOPPING_CART_SRV/ProductimageSet"));
oFileUploader1.upload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
});
oFileUploader.placeAt("content");
btnSubmit.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
Hi Jenish Prabhu
Actually i am trying to write a logic to upload a xlsx file, and the bind the xlsx data into a table in Sap UI5 Side.
is it possible to do