Skip to Content
0

how to send attachments from frontend to backend in sapui5 ? I am using upload collection control.

Sep 24, 2017 at 06:00 PM

408

avatar image

drag and drop feature for uploading

10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

3 Answers

Irfan Gokak Sep 25, 2017 at 09:34 AM
0

Hi,

Use below sample code.

View:

<ui:FileUpload 
	acceptRequestHeader="application/json"
	id="fileuploadLV" 
	items="/dataitems"
	uploadUrl="/sap/opu/odata/sap/ZHR_ESS_TM_LEAVE_SRV/AttachmentListSet"
	encodeUrl="/sap/bc/ui2/encode_file" 
	fileName="filename" 
	url="url"
	uploadedDate="uploaded" 
	contributor="contributor" 
	mimeType="mimeType"
	fileId="documentId" 
	deleteFile="onDeleteFile" 
	uploadFile="onUploadFile"
	fileUploadFailed="onFileUploadFailed" 
	beforeUploadFile="onBeforeUploadFile"
	showNoData="false" 
	useEditControls="true" 
	uploadEnabled="false"
	renameEnabled="false" 
	showAttachmentsLabelInEditMode="true"
	multipleSelectionEnabled="false">
							<ui:attachmentNumberLabel>
								<Label text="dummy txt"></Label>
							</ui:attachmentNumberLabel>
						</ui:FileUpload>

In Controller:

*-------------------------------------------------------
*	SET CSRF-Token
*-------------------------------------------------------	
	var oModel = this.getView().getModel();     
		oModel.mCustomHeaders["X-CSRF-Token"] = "Fetch";      
		var leaveTypeSet={};
		url = "/LeaveTypeSet";


		oModel.read(url, null, null, true, function(oData, oResponse) {
			that.busyDialog.close();
			oModel.oHeaders["x-csrf-token"] = oResponse.headers["x-csrf-token"];
			oModel.bTokenRequested = true;
			leaveTypeSet = oData;
			var data = {


					"leaveTypeSet" : leaveTypeSet


			};
			var jModel = new sap.ui.model.json.JSONModel(data);
			var leaveTypeId = that.getView().byId("leaveformTypeofLeaveId");
			leaveTypeId.setModel(jModel);
			delete oModel.mCustomHeaders["X-CSRF-Token"];
		}, function(err) {
			that.busyDialog.close();
			//execute in case of call fail
			var obj = JSON.parse(err.response.body);
			var msg = obj.error.message.value;
			var msgTitle="Error";
			sap.m.MessageBox.show(msg, {
				icon: sap.m.MessageBox.Icon.ERROR,
				title: msgTitle,
				actions: [sap.m.MessageBox.Action.OK],
			});	
		});
		
*----------------------------------------------------------
*Other Functions
*----------------------------------------------------------
onBeforeUploadFile : function(e) {


		var id = e.mParameters.id;
		var fileupload = sap.ui.getCore().byId(id);


		fileupload.setCustomHeader('slug', e.getParameters().name);
		fileupload.setXsrfToken(this.getView().getModel().oHeaders["x-csrf-token"]);
		var oFileUpload = that.getView().byId('fileuploadLV');
		var lbl=oFileUpload._oToolBar.getContent()[2];
		lbl.setText("PDF attachment");
		oFileUpload.setMultipleSelectionEnabled(false);
		that.getView().byId("fileuploadLV").setUploadEnabled(true);
	},


	/* handle on upload file event */
	onUploadFile : function(oEventData) {
		var id = oEventData.mParameters.id;
		var oData = oEventData.getParameters();
		var dataItem = new Object();
		//alert("Filename:"+oData.Fieldname)
		var fileupload = sap.ui.getCore().byId(id);
		//checking for file type and size
		if(oData.d != undefined){
			if(oData.d.FileName=="E_SIZE"){
				fileupload.abortUpload(); 
				sap.ca.ui.message.showMessageBox({
					type: sap.ca.ui.message.Type.ERROR,
					message: "File Size should be < 1 MB"
				});
				return;
			}else if(oData.d.FileName=="E_TYPE"){
				fileupload.abortUpload();
				sap.ca.ui.message.showMessageBox({
					type: sap.ca.ui.message.Type.ERROR,
					message: "Upload files with extension .pdf"
				});
				return;
			}else{


				dataItem.filename= oData.d.FileName;
//				dataItem.documentId=oData.d.Docid;
				if(window.location.href.substring(0, 5) != oData.d.__metadata.media_src.substring(0, 5)){
					oData.d.__metadata.media_src =
						window.location.href.substring(0, 6) + 
						oData.d.__metadata.media_src.substring(5, oData.d.__metadata.media_src.length);
				}


				dataItem.url=oData.d.__metadata.media_src;
				dataItem.mimeType = oData.d.ContentType;
				fileupload.commitFileUpload(dataItem);
			}  


		}else if(oData != undefined){
			if(oData.FileName=="E_SIZE"){
				fileupload.abortUpload(); 
				sap.ca.ui.message.showMessageBox({
					type: sap.ca.ui.message.Type.ERROR,
					message: "File Size should be < 1 MB"
				});
				return;


			}else if(oData.FileName=="E_TYPE"){
				fileupload.abortUpload();
				sap.ca.ui.message.showMessageBox({
					type: sap.ca.ui.message.Type.ERROR,
					message: "Upload files with extension .pdf"
				});
				return;
			}else{
				dataItem.filename= oData.FileName;
//				dataItem.documentId=oData.Docid;
				dataItem.mimeType = oData.ContentType;
				dataItem.url=oData.__metadata.media_src;
				fileupload.commitFileUpload(dataItem);


			}
		}
		var oFileUpload = that.getView().byId('fileuploadLV');
		var lbl=oFileUpload._oToolBar.getContent()[2];
		lbl.setText("PDF attachment");
		that.getView().byId("fileuploadLV").setUploadEnabled(false);
	},




	/* handle on delete file event */
	onDeleteFile : function(oEventData) {
		var id = oEventData.mParameters.id;
		sap.ui.getCore().byId(id).removeFile(oEventData.mParameters.documentId);
		var model = this.getView().getModel();
		var fldName="";
		var sValidate="AttachmentListSet(' ')";
		model.remove(sValidate, null,null,false, function(oData, oResponse) {
			//alert("success");
		}, function(err) {
			var message= JSON.parse(err.response.body).error.message.value;
			sap.m.MessageBox.show(message,
					sap.m.MessageBox.Icon.ERROR,
			"Error");
		});
		var oFileUpload = that.getView().byId('fileuploadLV');
		var lbl=oFileUpload._oToolBar.getContent()[2];
		lbl.setText("PDF attachment");
		that.getView().byId("fileuploadLV").setUploadEnabled(true);


	},
Share
10 |10000 characters needed characters left characters exceeded
Arjun Biswas Sep 25, 2017 at 10:41 AM
0

Hello,

You can use the file uploader, on change trigger a method in the controller, and in that method, get the model's csrf token and, through AJAX, send the attachment to the backend.

The view :-

<u:FileUploader
			id="fileUploader"
			name="myFileUpload"
			width="400px"
			tooltip="Upload your file to the local server"
			uploadOnChange="true"
			uploadComplete="handleUploadComplete">			 
			<u:parameters>
			<u:FileUploaderParameter
						name="type"
						value="image/jpeg"/>
			</u:parameters>
		</u:FileUploader>

The controller :-

handleUploadComplete:function(evt){
				var oFileUpload = sap.ui.getCore().byId("fileUploader");
				var f = evt.oSource.oFileUpload.files[0];
				var entry = {};
				entry.Photo = f;
				
				var url="your-service-url/userPhotoSet('"+this._id+"')/$value";
		        //var oRequest = this.getView().getModel()._createRequest();
		        var oHeaders = {
		                  "x-csrf-token": this._token
		        };
		        
		        jQuery.ajax({
		                  type: 'PUT',
		                  url:url,
		                  headers: oHeaders,
		                  cache: false,
		                  contentType: false,
		                  processData: false,
		                  data: f,
		                  success:function(){},
		                  error:function(err){console.log(err);}
		        });


			},
Share
10 |10000 characters needed characters left characters exceeded
Joseph BERTHE Sep 25, 2017 at 05:33 AM
0

Hello,

Did you look for the Sample provided by SAP in the SDK ?

The first thing you should do is to create an OData service with the Create stream method implemented, then set the URL of your UI Control to the OData.

Please look at this blog : Using the SAPUI5 UploadCollection to upload/download ArchiveLink files via Gateway

Regards,

Joseph

Share
10 |10000 characters needed characters left characters exceeded