openui5 FileUploader not working - file-upload

I am trying to upload a file with a simple form. I can choose a file but when I click on "upload" nothing happens.
My FileUploader.view.xml is like:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
My Contoller.controller.js
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
var ControllerController = Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
oFileUploader.upload();
}
});
return ControllerController;
});
When I run this in the debugger I get an Uncaught TypeError:
Uncaught TypeError: Cannot read property '1' of null
at f.handleUploadComplete (FileUploader.controller.js?eval:11)
at f.a.fireEvent (EventProvider-dbg.js:229)
at f.a.fireEvent (Element-dbg.js:427)
at f.fireUploadComplete (ManagedObjectMetadata-dbg.js:426)
at HTMLIFrameElement.eval (FileUploader.js?eval:6)
at HTMLIFrameElement.dispatch (jquery-dbg.js:4737)
at HTMLIFrameElement.c3.handle (jquery-dbg.js:4549)
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
I searched for sample code and it seems my code is ok, but I don't know why I can't upload a file by click on the button.

I solved this problem ! :)
So, instead of using this
var m = /^[(\d\d\d)]:(.)$/.exec(sResponse);
use this in view FileUploader :
sendXHR="true"
After, on controller js you can use for status :
oEvent.getParameter("status")
and for getting answer as a json file :
var jsonfile = JSON.parse(oEvent.getParameter("responseRaw"));
Then access your sent object attributes from server (only when use dataType: 'json')
jsonfile.attribute
I hope this helps a lot!

Related

Python selenium close modal window after reading its content

I have the HTML as following:
function showModal(msg) {
var content = document.getElementById("modal-content");
content.innerHTML = msg;
modal.style.display = "block";
}
showModal(msg + "<br>Job started, check status on the project jobs page.");
After all is said and done, I get the following window:
How do I read the content of the box and if there is "Success" I can click the close on top right to go back to the previous page.
I don't have a clue how to approach this.
Edit: Extended HTML looks as following:
function makeInputScenario(ids,params,has_extra = false) {
var sd = gete("sdate").value;
var ed = gete("edate").value;
var sdt = new Date(sd);
var edt = new Date(ed);
if (sdt > edt) {
showModal("Start date is after end date, please fix!");
return;
}
var p = gete("pool").value;
var dzr = gete("dzr").value;
var pfd = gete("pfd").value;
var udb = gete("udb").value;
var uds = gete("uds").value;
if (uds == "None") uds = "";
var rop = gete("rop-text").value;
var fuds = gete("fuds").value;
if (fuds == "None") fuds = "";
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
hideProgress();
if (!params) setInteraction(false);
if (xhr.status == 200) {
var msg = "<strong>SUCCESS:</strong><br><pre>" + xhr.responseText + "</pre>"
showModal(msg);
if (params) {
if (has_extra) {
showProgress("Processing, please wait...");
doAction("run-params","POST","/scenario/run","user=PJMRTO LONG RUN AUCTION" + params + "&cir=" + getCir(),function (ret) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<p>" + ret + "</p>");
});
} else {
var ods = gete("ods").value;
showProgress("Adding new job, please wait...");
doAction("run-params","POST","/job","user=PJMRTO LONG RUN AUCTION&sdate=" + sd + "&edate=" + ed + "&ids=" + ids + "&ods=" + ods + "&rops=" + encode(rop) + "&post=" + encode("") + "&std=" + encode("") + "&cir=" + getCir(),function (job) {
showProgress("Starting job " + job + ", please wait...");
doAction("run-params","POST","/run","id=" + job + params,function (x) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<br>Job started, check status on the project jobs page.");
});
});
}
}
} else if (xhr.status == 500) {
setInteraction(false);
clearTimeout(updProgrs);
var logurl = "/idblog?q=host&name=" + encode(ids) + "&pool=" + encode(p) + "&sd=" + encode(sd) + "&ed=" + encode(ed);
showModal(wrapError("<pre>" + xhr.responseText + "</pre><br><button onclick=\"getIDBlog('" + logurl + "');\" class=\"btn btn-primary\">Download Log</button>"));
}
},false);
setInteraction(true);
if (params) {
gete("start-job").style.display = "none";
gete("host-status").style.display = "none";
}
var sparams = "user=PJMRTO LONG RUN AUCTION&pool=" + p + "&dzr=" + dzr + "&pfd=" + pfd + "&ids=" + ids + "&sdate=" + sd + "&edate=" + ed + "&udb=" + udb + "&uds=" + uds + "&rop=" + encode(rop);
if (fuds != "") {
sparams += "&fuds=" + fuds + "&ius=" + gete("ods").value;
showProgress("Creating base and fixed UC input scenarios, please wait...");
} else {
showProgress("Creating input scenario, please wait...");
}
updProgrs = setTimeout(updateProgress, 300000);
xhr.open("POST","/scenario",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-csrf-token","NhISQUB1eCANGh46HwsgTnsAISkCAAAATeFn4B0myInXzZc7+8QJMA==");
xhr.send(sparams);
}
So here variable "msg" is storing the value "SUCCESS". It would be better to get the variable "msg" usin javascript.
So that would be :-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://Reachyourpage")
message = driver.execute_script("return msg")
print ("SUCCESS" in message)
It should return true in case of success. I am no expert in Python but just a beginner so mind my coding.. !!
C# equivalant here would be :-
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
string title = js.ExecuteScript("return msg");
Here, title will have the complete message.
The algorithm is to get the value of "msg" var using javascript.
For Closing the message, have u tried using SendKeys(Keys.Esc) ??
Hope it Helps!!

Getting Bad method 405 response while trying to upload a file to Google Cloud Storage using SAP ui5

I am trying to upload a file to Google Cloud Storage using a basic uploader in UI5.
When I am uploading the file, I am getting a 405 error in my response.
My controller code goes like this.
Please let me know if I am making any mistake anywhere.
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
return Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function() {
var oFileUploader = this.byId("fileUploader");
var prop = oFileUploader.getValue();
var path = oFileUploader.getUploadUrl();
MessageToast.show(prop);
MessageToast.show(path);
// var form = new FormData();
//form.append("files", fileInput.files[0],"C:\Users\i347520\Desktop\pan.jpg");
/*eslint-disable*/
var settings = {
"url": "https://storage.googleapis.com/upload/storage/v1/b/testocr-1234/o?uploadType=media&name=prop"
/*eslint-enable*/
};
oFileUploader.upload(settings);
}
});
});
View:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
</mvc:View>

Google App Script custom error on .withFailureHandler

I would like to throw a custom error in a function called with google.script.run from code.gs so I could display adequate information in a side bar. So far I've tested the following code with no luck:
code.gs
function UserException(type, text) {
this.type = type;
this.text = text;
//this.stack = (new Error()).stack;
}
UserException.prototype = Object.create(Error.prototype);
UserException.prototype.constructor = UserException;
function assignRangeToTechnician(technician)
{
if(technician!=null)
{
//some code
}else
throw new UserException("Error","Technician was not selected");
}
sidebar.html
...
<script>
function btnSelectTech()
{
google.script.run
.withSuccessHandler(rangeSelected)
.withFailureHandler(techniciansMessage)
.assignRangeToTechnician(document.getElementById('selectTechnician').value);
}
function techniciansMessage(Message)
{
var outputMessage = document.getElementById('message');
//here is where I log the Message value
google.script.run.myLog("In techniciansMessage() - Message: " + Message);
if (Message == null)
outputMessage.innerHTML = "<p style='color:red;'>Error occured</p>";
else
if (Message.type == "Error")
outputMessage.innerHTML = "<p style='color:red;'>" + Message.text + "</p>";
else if (Message.type == "Message")
outputMessage.innerHTML = "<p style='color:#f3f3f3;'>" + Message.text + "</p>";
}
</script>
...
When I run the code the .withFailureHandler is called but the Message doesn't hold the proper value. When I log that message I read "Error: " as a content of a 'Message' parameter.
Could you please help?
Thank you.
You may refer with this SO thread. Try adding an error parameter to your function. Example:
google.script.run.withFailureHandler(function (error) {
showError(error, 'getMe');
}).getMe();
Additional reference which might help: https://github.com/google/google-apps-script-samples/blob/master/translate/Sidebar.js.html

How to save or open a pdf file in pdf Viewer from response titanium

I want to open pdf file on click.
I tried below code but it didn't help me. It is giving error could not read file
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'file.pdf');
Ti.API.info('file == ' + f);
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
f.write(this.responseData);
Ti.API.info('write file == ' + f.write(this.responseData));
Ti.API.info('filepath == ' + f.nativePath);
Ti.API.info('get filepath == ' + f.getNativePath());
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : f.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();
But I am getting Error as The document path is not valid.
I tried different way also using webview still not getting pdf on my app.
var win = Ti.UI.createWindow({
backgroundColor : '#fff'
});
var pdfViewer = Ti.UI.createWebView({
url : "http://lkn.ccomsys.com/assets/media/datafiles/gov/vvvv_Shehnai_Order1.pdf",
width : Titanium.UI.SIZE,
height : Titanium.UI.SIZE
});
Ti.API.info('pdfviewer == ' + JSON.stringify(pdfViewer));
win.add(pdfViewer);
win.open();
Thanks in advance.
I sorted this out
Step 1 : Created directory and file.
Step 2 : Write response to created file.
Step 3 : Open pdf with android intent.
Below is the complete code
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Alloy.Globals.loading.hide();
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
Ti.API.info("Created Settings: " + Settings.createDirectory());
Ti.API.info('Settings ' + Settings);
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Setting.pdf');
Ti.API.info('new file == ' + newFile);
if (newFile.exists() === false) {
// you don't need to do this, but you could...
newFile.write(this.responseData);
}
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
if (newFile.exists()) {
newFile.write(this.responseData);
Ti.API.info('newfile: ' + newFile.read());
}
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : newFile.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();

How can I Recursively Read Files and Folders using JavaScript

I've just started discovering Windows StoreApps (that's what Microsoft calls it) and I'm following the sample code here about using the FolderPicker.
I want to Iterate through the folder and read all the sub-folders and files.
There are two functions I've looked at which I thought are what I need but I'm not able to do it properly after trying hours.
In the link above, the line which says:
WinJS.log && WinJS.log("Picked folder: " + folder.name, "sample", "status");
I tried to dig deeper in the folder with something like:
folder.getFoldersAsync().then(function (folderItem) {
document.getElementById('musicFolder').innerHTML += folderItem.length + " folders)<br/>";
folderItem.forEach(function (x) {
document.getElementById('musicFolder').innerHTML += "--" + x.name + "<br/>";
x.getFilesAsync().then(function (items) {
document.getElementById('musicFolder').innerHTML += items.length + " files"+"<br>";
});
});
});
UPDATE:
I have been struggling but can't get the stuff organized while iterating folders and sub-folders.
#Damir's code doesn't dig deepest folder. We need a recursive function. I could come up with the following function but as I said result is not organized
function scanFolder(folder) {
var isInc = false;
folder.getFoldersAsync().then(function (folderItem) {
if (folderItem.length > 0) {
folderItem.forEach(function (x) {
if (!isInc) {
isInc = true;
hyphen += "-";
}
document.getElementById('musicFolder').innerHTML += hyphen + x.name + "</br>";
x.getFilesAsync().then(function (items) {
items.forEach(function (item) {
allTracks.push({
name: item.name,
path: item.path
});
document.getElementById('musicFolder').innerHTML += hyphen +"-"+ item.name + "</br>";
});
}).done(function () {
scanFolder(x);
});
});
}
});
}
You want to read all the subfolders and the files inside them? Something like this should work:
folder.getFoldersAsync().then(function (folderItem) {
document.getElementById('musicFolder').innerHTML += "(" + folderItem.length + " folders)<br/>";
folderItem.forEach(function (x) {
x.getFilesAsync().then(function (items) {
document.getElementById('musicFolder').innerHTML += "--" + x.name + " (" + items.length + " files)<br>";
items.forEach(function(item) {
document.getElementById('musicFolder').innerHTML += "----" + item.name + "<br>";
});
});
});
});
EDIT:
There's actually no need for recursion to recursively scan a folder and its subfolders in WinRT. You can use StorageFolder.CreateFileQueryWithOptions() instead:
var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.defaultQuery, ['*']);
options.folderDepth = Windows.Storage.Search.FolderDepth.deep;
folder.createFileQueryWithOptions(options).getFilesAsync().then(function (files) {
var paths = new Array();
files.forEach(function(file) {
paths.push(file.path);
});
paths.sort();
paths.forEach(function(path) {
document.getElementById('musicFolder').innerHTML += path + "<br>";
});
});
From here on you can transform the flat list of files to whatever you need instead of just printing out their path.