How to Upload files in SAPUI5? - upload

How to upload file in SAP Netweaver server using SAPUI5? I tried to upload file using FileUploader but did not get the luck if any one can help it will be very appreciated.
Thanks in Advance

Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.
UploadFile.view.xml
<VBox>
<sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
Controller, MessageToast, MessageBox, History) {
"use strict";
return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
onNavBack: function() {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("admin", true);
}
},
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
});
});

After researching a little more on this issue I finally solved this issue by myself I placed a file controller and a uploader in php which return the details related to files further, we can use it to upload it on server.
Here is the code I have used.
fileUpload.html
<!DOCTYPE html>
<html><head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<title>Hello World</title>
<script id='sap-ui-bootstrap' src='http://localhost/resources/sap-ui-core.js' data-sap-ui-theme='sap_goldreflection'
data-sap-ui-libs='sap.ui.commons'></script>
<script>
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader("myupload",{
name: "upload2",
uploadOnChange: true,
uploadUrl: "uploader.php",
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
alert(sResponse);
}
}});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text:'Trigger Upload',
press:function() {
// call the upload method
oFileUploader2.upload();
$("#myupload-fu_form").submit();
alert("hi");
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");
</script>
</head>
<body class='sapUiBody'>
<div id="sample2"></div>
</body>
</html>
uploader.php
<?php
print_r($_FILES);
?>

It would be good if we can see your code.
This should work.
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader({
name : "upload2",
uploadOnChange : false,
uploadUrl : "../../../upload"
});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text : 'Trigger Upload',
press : function() {
// call the upload method
oFileUploader2.upload();
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");

Related

select2 v4 dataAdapter.query not firing

I have an input to which I wish to bind a dataAdapter for a custom query as described in https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection
<input name="pickup_point">
My script:
Application.prototype.init = function() {
this.alloc('$pickupLocations',this.$el.find('[name="pickup_point"]'));
var that = this;
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
var CustomData = function($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
results: []
};
console.log("xxx");
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
that.$pickupLocations.select2({
minimumInputLength: 2,
language: translations[that.options.lang],
tags: [],
dataAdapter: CustomData
});
});
}
But when I type the in the select2 search box the xxx i'm logging for testing doesn't appear in my console.
How can I fix this?
I found the solution on
https://github.com/select2/select2/issues/4153#issuecomment-182258515
The problem is that I tried to initialize the select2 on an input field.
By changing the type to a select, everything works fine.
<select name="pickup_point">
</select>

Parsing an xmlhttpresponse to retrieve a value

I've managed to read the response but I've been stuck for hours now trying to just get the "balance" value.
How do I parse out just the 23 number? (that's the balance in this case)
<!DOCTYPE html>
<html>
<body>
<p id="data"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("data").innerHTML =
xhttp.responseText;
}
};
xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
xhttp.send();
</script>
</body>
</html>
Here is an example how to retrieve balance with JSON.parse:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var objResp = JSON.parse(xhttp.responseText);
document.getElementById("data").innerHTML = objResp.balance // 23
}
};
xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
xhttp.send();
Or you can even use eval method, but that solution is not so reliable since responce might contain malicious code which will be executed:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var objResp = eval('('+xhttp.responseText+')');
document.getElementById("data").innerHTML = objResp.balance // 23
}
};
xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
xhttp.send();

Preview an image before it is saved to database in Yii using Jquery

I am not understanding how should I carry on to Preview an image before it is
being saved to database in yii using jquery or any method that you can suggest
view
<img id="preview_image"
src="images/<?php echo $model->pimg; ?>"
width="150px" height="120px"/>
<?php echo $form->labelEx($model,'pimg'); ?>
<?php echo $form->fileField($model, 'pimg',array('change'=>preview(this));); ?>
<?php echo $form->error($model,'pimg'); ?>
the jquery code
function preview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview_image')
.attr('src', e.target.result)
.width(100)
.height(120);
};
reader.readAsDataURL(input.files[0]);
}
}
Fatal error to function call preview().
How should I integrate this Jquery function in above form ....... $form has the htmlOptions
PLEASE HELP! I am new to Yii and am loosing my mind on this. Thank you.
This bellow code shows the image preview using jQuery
var imageTypes = ['jpeg', 'jpg', 'png']; //Validate the images to show
function showImage(src, target)
{
var fr = new FileReader();
fr.onload = function(e)
{
target.src = this.result;
};
fr.readAsDataURL(src.files[0]);
}
var uploadImage = function(obj)
{
var val = obj.value;
var lastInd = val.lastIndexOf('.');
var ext = val.slice(lastInd + 1, val.length);
if (imageTypes.indexOf(ext) !== -1)
{
var id = $(obj).data('target');
var src = obj;
var target = $(id)[0];
showImage(src, target);
}
else
{
}
}
And your HTML should be
<input type="file" name="image" onchange="uploadImage(this)" data-target="#aImgShow" />
<img id="aImgShow" src="" class="carImage" />

loading flickr photos by a set in div jquery mobile

i am creating a jquery mobile application;this is the script to load flickr photos thumbnail in a div it is loading but it is appearing in a group thumbnail not loading each images.can load each thumbnails by editing this.i just removed my api key and my ids.
$(function() {
var api_key = 'API KEY';
var user_id = 'ID';
var photoset_id = 'PHOTO SET ID';
var large_image_size = 'Medium';
var photoset_id,photo_id;
var current = -1;
var continueNavigation = false;
var photos_service = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos' + '&api_key=' + api_key;
var photos_url = photos_service + '&photoset_id=' + photoset_id + '&media=photos&format=json&jsoncallback=?';
var large_photo_service = 'http://api.flickr.com/services/rest/?&method=flickr.photos.getSizes' + '&api_key=' + api_key;
var $photosContainer = $('#images').find('#ba');
var $photopreview = $('#flickr_photopreview');
var $flickrOverlay = $('#flickr_overlay');
var $loadingStatus = $('.loading_small');
$(function(){
$('#images').stop().animate(200,function(){
if($photosContainer.is(':empty')){
/*
if sets not loaded, load them
*/
LoadPhotos();
}
});
},function(){
});
function LoadPhotos(){
$photosContainer.empty();
$loadingStatus.css('visibility','visible');
$.getJSON(photos_url,function(data){
if(data.stat != 'fail') {
var photo_count = data.photoset.photo.length;
var photo_count_total = photo_count ;
for(var i = 0; i < photo_count; ++i){
var photo = data.photoset.photo[i];
var photoid = photo.id;
var secret = photo.secret;
var server = photo.server;
var farm = photo.farm;
var photoUrl = 'http://farm'+farm+'.static.flickr.com/'+server+'/'+photoid+'_'+secret+'_s.jpg';
var $elem = $('<div />');
var $link = $('<a class="toLoad" href="#" />');
$link.data({
'photoid' :photoid,
'secret' :secret,
'server' :server,
'farm' :farm,
'photoUrl' :photoUrl,
'photo_title' :photo.title
});
$photosContainer.append($elem.append($link));
$link.bind('click',function(e){
var $this = $(this);
current = $this.parent().index();
photo_id = $this.data('photoid');
LoadLargePhoto();
e.preventDefault();
});
}
LoadPhotosImages();
}
});
}
function LoadPhotosImages(){
var toLoad = $('.toLoad:in-viewport').size();
if(toLoad > 0)
$loadingStatus.css('visibility','visible');
var images_loaded = 0;
$('.toLoad:in-viewport').each(function(i){
var $space = $photosContainer.find('.toLoad:first');
var $img = $('<img style="display:none;" />').load(function(){
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
}
}).error(function(){
//TODO
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
}
}).attr('src',$space.data('photoUrl'))
.attr('alt',$space.data('photoid'));
var $photo_title = $('<span/>',{'html':$space.data('photo_title')});
$space.append($photo_title).append($img).removeClass('toLoad');
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/jquery-latest.js"></script>
<script type="text/javascript">
function downloadImg() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
ids : "78368944#N06",
tags: "",
tagmode: "any",
format: "json",
},
function(data) {
$('.img-1').attr('src', data.items[0].media.m);
$('.tit-1').text(data.items[0].title);
$('.img-2').attr('src', data.items[1].media.m);
$('.tit-2').text(data.items[1].title);
}
);
}
$(document).ready(function() {
downloadImg();
});
</script>
</head>
<body>
<div class="img-cont"><img class="img-1" /> </div>
<h3 class="tit-1"></h3>
<div class="img-cont"><img class="img-1" /> </div>
<h3 class="tit-1"></h3>
</body>
</html>

$.ajax({url:link}) and Jquery UI Droppable

I have a problem.
I drop element into #projectsActive. New element have been created there. Old element have been deleted with fadeOut
But ajax query sometimes isn't running.
What's the reason?
$("#projectsActive").droppable({
drop: function (event, elem)
{
var e = elem.draggable;
var linkToSend = "/Projects/Publish/" + $(e).attr("projectid");
$.ajax({ url: linkToSend });
var projectid = $(e).attr("projectid");
var innerText = "";
if ($(e).find("a").length > 0)
{
innerText = $(e).children("a").html();
}
else
{
innerText = $(e).html();
}
var newObject = '<li class="project dragg" projectid="' + projectid + '">' + innerText + '</li>';
$(e).fadeOut("fast", function ()
{
$("#projectsActive").append(newObject);
$(this).remove();
BindDrags();
});
}
});

Resources