Uploading a file using the File Uploader module - sapui5

I am trying to upload a file using the FileUploader module in SAPUI5. The code I am trying to follow is from a blog https://blogs.sap.com/2016/11/08/step-by-step-on-how-to-use-the-sapui5-file-upload-feature/ however the code does not seem to execute the reader.onload function? It gets to reader.readAsDataURL(file) and dose not do anything? I am not sure where the problem lies and how to get it to work? Hekp will be much appreciated, there is a similar issue in the blog response but no help has been given.
XML
<u:FileUploader
id="VRCFileUploader"
value="{VRCFileUpload}"
placeholder="Please Attach document"
fileType="jpg,png,pdf"
style="Emphasized"
useMultipart="false" >
</u:FileUploader>
JS
function upload(evnt) {
var token;
var oView = this.getView();
var oFileUploader = this.byId("VRCFileUploader");
var sFileName = oFileUploader.getValue();
if (sFileName === "") {
sap.m.MessageToast.show("Please select a File to Upload");
return;
}
var file = jQuery.sap.domById(oFileUploader.getId() + "-fu").files[0];
var base64_marker = "data:" + file.type + ";base64,";
var reader = new FileReader();
//on load
reader.onLoad = (function(theFile){
return function(evt) {
//locate base64 content
var base64Index = evt.target.result.indexOf(base64_marker) + base64_marker.lenght;
// get base64 content
var base64 = evt.target.result.substring(base64Index);
var sTasksService = "SOME URL";
var sService2 = "SOME URL";
var oViewModel = oView.getModel();
var oContext = oView.getBindingContext();
var oTask = oViewModel.getProperty(oContext.getPath());
var oDataModel = sap.ui.getCore.getModel();
var sWorkitemId = JSON.stringify(oTask.wiId);
var service_url = sService2;
$.ajaxsetup({
cache: false
});
jQuery.ajax({
url: service_url,
asyn: false,
datatype: "json",
cache: false,
data: base64,
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader("x-csrf-Token", token);
xhr.setRequestHeader("content-Type", file.type);
xhr.setRequestHeader("slug", sFileName);
xhr.setRequestHeader("WorkitemId", oTask.WiId);
},
success: function(odata) {
sap.m.MessageToast.show("file successfully uploaded");
oFileUploader.setValue("");
},
error: function(odata) {
sap.m.MessageToast.show("file Upload error");
}
});
};
})(file);
//Read file
reader.readAsDataURL(file);
}
In reply to Vortex:

Why is there an IIFE on the method being used on the onLoad Property?
Try to do somenthing like this:
reader.onload = event => {
let fileAsDataUrl = event.target.result;
....
};

Related

upload file into document library in sharepoint with column value

Iam trying to upload file into document library but I can able to upload file but however column data was not reflecting into the column of document library.using rest Api every thing is working but my column value was not showing inside the column
here is my code
function createListItem() {
debugger;
var files = $("#attachment")[0].files;
if (files.length > 0) {
fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "MyDocumets";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type},
"DocumentType": $('#documenttype').val(),
"DocumentDescription": $("#Description").val(),
FileLeafRef: DocFileName //FileLeafRef --> Internal Name for Name Column
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!")
}
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
// Get the local file as an array buffer.
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
i wanted to know how to enter value into the column and upload the document at the sane time

Mapping List with Knockout Mapping

I have created view model
var catalog = ko.observableArray();
$.ajax({
type: "GET",
url: "http://localhost:8080/ticket-service/rest/ticket/list",
success: function(msg) {
catalog.push.apply(catalog, $.map(msg, function(data) {
return new Ticket(data)
}));
return catalog;
},
error: function(msg) {
console.log(msg)
}
});
and the model
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
this.ticketNo = ko.observable(data.ticketNo);
this.ticketTitle = ko.observable(data.ticketTitle);
this.longDescription = ko.observable(data.longDescription);
this.createdBy = ko.observable(data.createdBy);
this.createdOn= ko.observable(data.createdOn);
this.assignTo = ko.observable(data.assignTo);
this.priority = ko.observable(data.priority);
this.dueDate = ko.observable(data.dueDate);
this.status = ko.observable(data.status);
this.projectId = ko.observable(data.projectId);
}
with at the end viewmodel like this
return {
ticket: newTicket,
searchTerm: searchTerm,
catalog: filteredCatalog,
newTicket: newTicket,
addTicket: addTicket,
delTicket: delTicket
};
})();
console.log(vm);
ko.applyBindings(vm);
produce list,add, and delete form.The question is how can i use knockout mapping that can list from get methode.
you need to do something like this
Demonstrated taking a single entity from your code .
view:
Output Preview :
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
viewModel:
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
}
var mapping = {
create: function (options) {
return new Ticket(options.data);
}
};
var ViewModel = function () {
var self = this;
self.catalog = ko.observableArray();
var data = [{
'ticketId': 1
}, {
'ticketId': 2
}]
//under ajax call do the same but pass 'msg' in place of data
self.catalog(ko.mapping.fromJS(data, mapping)())
console.log(self.catalog()); // check console for output
};
ko.applyBindings(new ViewModel());
sample working fiddle here

How to insert a blob into mongodb in meteor

I am using Recorder.js, which allows you to display an audio recording like so
recorder.exportWAV(function(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
au.controls = true;
au.src = url;
}
But how can I save the blob to the database? Assuming I have a Recordings collection:
recorder.exportWAV(function(blob) {
Recordings.insert({data: blob});
}
will only store this
{data: { "type" : "audio/wav", "size" : 704556 }}
which does not have the actual content.
After watching the file upload episode from eventedmind.com, it turns out the way to do it is to use the FileReader to read a blob as ArrayBuffer, which is then converted to Uint8Array to be stored in mongo:
var BinaryFileReader = {
read: function(file, callback){
var reader = new FileReader;
var fileInfo = {
name: file.name,
type: file.type,
size: file.size,
file: null
}
reader.onload = function(){
fileInfo.file = new Uint8Array(reader.result);
callback(null, fileInfo);
}
reader.onerror = function(){
callback(reader.error);
}
reader.readAsArrayBuffer(file);
}
}
The exportWAV callback is then
recorder.exportWAV(function(blob) {
BinaryFileReader.read(blob, function(err, fileInfo){
Recordings.insert(fileInfo)
});
});
Then I can display one of my recordings by:
Deps.autorun(function(){
var rec = Recordings.findOne();
if (rec){
var au = document.createElement('audio');
au.controls = true;
var blob = new Blob([rec.file],{type: rec.type});
au.src = URL.createObjectURL(blob);
document.getElementById("recordingslist").appendChild(au);
}
})
I don't know if the previous snippet works in other browsers, but this may:
var base64Data = btoa(String.fromCharCode.apply(null, rec.file))
var au = document.createElement('audio');
au.controls = true;
au.src = "data:"+rec.type+";base64,"+base64Data
Just in case, did you notice this line in their example
Make sure you are using a recent version of Google Chrome, at the
moment this only works with Google Chrome Canary.
I will soon need to look into this for my own project, hope you get it running.

SAP HANA XS File upload with UI5

I'm trying to implement a file upload in a UI5 application on a HANA XS Server.
I can't find many informations how to do that - somebody got an idea?
here's the simple implementation of a plain text file upload:
Client side js:
doUpload: function() {
var uploadField = document.getElementById("ulUploader1-fu");
var file = uploadField.files[0];
var reader = new FileReader();
reader.onload = function (event) {
var source = event.target.result; // this is the binary values
var name = file.name;
$.ajax({
url: "/services/upload.xsjs?cmd=Import",
type: "PUT",
processData: false,
contentType: file.type,
data: source,
xhr: function() {
var req = $.ajaxSettings.xhr();
if (req) {
if (req.overrideMimeType) {
req.overrideMimeType('text/plain; charset=x-user-defined');
}
if (req.sendAsBinary) {
req.send = req.sendAsBinary;
}
}
return req;
},
error: function(xhr, textStatus, errorThrown){
alert(xhr.responseText);
},
success: function() {
reader.onload = null;
}
});
};
reader.readAsText(file);
}
And here's the serverside xsjs service:
function doImport() {
var data = '', conn = $.db.getConnection(), pstmt;
if($.request.body){
data = $.request.body.asString();
}
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( 'INSERT INTO "TEST"."UPLOAD" (ID, MIMETYPE, DATA) VALUES(?,?,?)' );
pstmt.setInteger(1,1);
pstmt.setString(2,"text/plain");
pstmt.setString(3,data);
pstmt.execute();
pstmt.close();
conn.commit();
conn.close();
doResponse(200,'');
$.response.contentType = 'text/plain';
$.response.setBody('Upload ok');
$.response.status = 200;
}
There is no "ready-to-consume" service from XS that allows you to do that. You can of course create a table in HANA DB, create a column-type BLOB and then build service on XS that allows you to upload file from your front-end. I hope that helps.

how do i make a jquery plugin

I'm trying to make a jquery plugin
but it's not working what a'm i doing wrong
(function($){
$.fn.rss({
//pass the options variable to the function
rss: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
feedUrl: ''
}
var options = $.extend(defaults, options);
return this.each(function() {
var Setting = options;
//code to be inserted here
$.ajax({
type: "GET",
url: Setting.feedUrl,
dataType: "xml",
success: function(xml) {
$(xml).find('channel').each(function(){
$(xml).find('image').each(function(){
var title2 = $(this).find('title').text();
var url2 = $(this).find('link').text();
$('<div class="title"></div>').html(''+title2+'').fadeIn(1000).appendTo('#title');
});
$(xml).find('item').each(function(){
var title = $(this).find('title').text();
var brief = $(this).find('description').text();
var url = $(this).find('link').text();
$('<div class="items"></div>').html('<div class="dis">'+brief+'</div>').fadeIn(1000).appendTo('#blab');
});
});
}
});
});
}
});
})(jQuery)
By writing $.fn.rss(...), you're calling a non-existent function.
You need to create a function by writing
$.fn.rss = function(...) { ... };