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.
Related
The example from github doesn't work for me.
https://github.com/nightwatchjs/nightwatch/issues/369
This is my code.
When('I open a new browser window', () => {
var host = 'http://www.google.com';
client
.windowHandle(function(wh){console.log(wh.value)})
.url(host)
.waitForElementVisible('#hplogo', 1000)
.execute(function(newWindow){
window.open('http://www.twitter.com', null, "height=1024,width=768");
}, [host])
.assert.urlContains('google')
.window_handles(function(result) {
var temp = result.value[1];
this.switchWindow(temp);
})
.windowHandle(function(wh){console.log(wh.value)})
.assert.urlContains('twitter')
.end();
});
Both console.log before and after .switchWindow print out the same string.
Does anyone have any ideas please...?
EDIT
I've changed the code a bit taking into account what pcalkins said.
This is the code now:
When('I open a new browser window', () => {
var host = 'http://www.google.com';
client
.windowHandle(function(wh){console.log("\nBEFORE: " + wh.value)})
.url(host)
.waitForElementVisible('#hplogo', 1000)
.execute(function(newWindow){
window.open('http://www.twitter.com', null, "height=1024,width=768");
}, [host])
.pause(3000)
.window_handles(function(result) {
console.log("\n\nHANDLE: " + result.value + "\n");
var temp = result.value[0];
this.switchWindow(temp);
console.log("\n\ntemp0: " + temp + "\n");
temp = result.value[1];
this.switchWindow(temp);
console.log("\n\ntemp1: " + temp + "\n");
})
.pause(2000);
});
When run, this is the result:
BEFORE is the handle for the original window.
HANDLE is both windows.
temp0 and temp1 are the two different windows in sequence. Clearly temp1 is the window I want, and yet the final this.switchWindow is not doing its job.
AFTER is the current window handle at the next test step.
I tried to get all the files and directories available in a folder using react-native-fs.
I created a function to get all the files and directories recursively in a folder, I call this function this way :
const data = await scanDir(path);
I first tried using the .map() function but my function return only some elements :
async function scanDir(pathOfDirToScan, data = {directory: [], files: []}) {
const readedFilesAndDir = await FS.readDir(pathOfDirToScan);
Object.keys(readedFilesAndDir).map(async key => {
if (readedFilesAndDir[key].isDirectory()) {
const directoryPath = pathOfDirToScan + '/' + readedFilesAndDir[key].name;
data.directory.push(directoryPath);
data = await scanDir(directoryPath, data);
} else {
data.files.push(pathOfDirToScan + '/' + readedFilesAndDir[key].name);
}
});
return data;
}
It seems my function return the data after the first time map is executed, but the function continue after that.
I then tried with a for loop and it works as intended :
async function scanDir(pathOfDirToScan, data = {directory: [], files: []}) {
const readedFilesAndDir = await FS.readDir(pathOfDirToScan);
for (let i = 0; i < readedFilesAndDir.length; i++) {
if (readedFilesAndDir[i].isDirectory()) {
const directoryPath = pathOfDirToScan + '/' + readedFilesAndDir[i].name;
data.directory.push(directoryPath);
data = await scanDir(directoryPath, data);
} else {
data.files.push(pathOfDirToScan + '/' + readedFilesAndDir[i].name);
}
}
return data;
}
What should I do to make the function properly works using .map() ?
The FS.readDir(dirpath) returns an array of objects as per docs. Object.keys(obj) is not required for iteration in that case, just readedFilesAndDir.map() will do your task.
Copy and pasted your own code with some corrections. Hope, it helps:
async function scanDir(pathOfDirToScan, data = {directory: [], files: []}) {
const readedFilesAndDir = await FS.readDir(pathOfDirToScan);
readedFilesAndDir.map(async eachItem=> {
if (eachItem.isDirectory()) {
const directoryPath = pathOfDirToScan + '/' + eachItem.name;
data.directory.push(directoryPath);
data = await scanDir(directoryPath, data);
} else {
data.files.push(pathOfDirToScan + '/' + eachItem.name);
}
});
return data;
}
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>
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!
I have a programmer class that populates a ul with project names and checkboxes - when a checkbox is clicked a popup dialog is supposed to show with the programmers id and the project name. dojo.connect is supposed to setup onclick for each li but the project (i) defaults to the last value (windows). Any ideas why this is happening?
...
projects: {"redial", "cms", "android", "windows"},
name: "Chris",
id: "2",
constructor: function(programmer) {
this.name = programmer.name;
this.id = programmer.id;
this.projects = programmer.projects;
},
update: function(theid, project) {
alert(theid + ", " + project);
},
postCreate: function() {
this.render();
// add in the name of the programmer
this.programmerName.innerHTML = this.name;
for(var i in this.projects) {
node = document.createElement("li");
this.programmerProjects.appendChild(node);
innerNode = document.createElement("label");
innerNode.setAttribute("for", this.id + "_" + i);
innerNode.innerHTML = i;
node.appendChild(innerNode);
tickNode = document.createElement("input");
tickNode.setAttribute("type", "checkbox");
tickNode.setAttribute("id", this.id + "_" + i);
if(this.projects[i] == 1) {
tickNode.setAttribute("checked", "checked");
}
dojo.connect(tickNode, 'onclick', dojo.hitch(this, function() {
this.update(this.id, i)
}));
node.appendChild(tickNode);
}
},
Just found out that extra parameters can be attached to the hitch:
dojo.connect(tickNode, 'onclick', dojo.hitch(this, function() {
this.update(this.id, i)
}));
should be:
dojo.connect(tickNode, 'onclick', dojo.hitch(this, "update", this.id, i));
Why are you calling this.render()? Is that your function or the widget base (i.e. already in the lifecycle)? For good measure make sure to call this.inherited(arguments); in postCreate.
My guess would be that tickNode is not in the DOM yet for the connect to work. Try appending the checkbox before you setup the connect. The last one is being fired because it is being held on by reference. You can try something like this instead:
for(var i = 0; i < this.projects.length; i++) {
var p = this.projects[i];
node = document.createElement("li");
this.programmerProjects.appendChild(node);
innerNode = document.createElement("label");
innerNode.setAttribute("for", this.id + "_" + p);
innerNode.innerHTML = p;
node.appendChild(innerNode);
tickNode = document.createElement("input");
tickNode.setAttribute("type", "checkbox");
tickNode.setAttribute("id", this.id + "_" + p);
if(i == 0) { //first item checked?
tickNode.setAttribute("checked", "checked");
}
node.appendChild(tickNode);
dojo.connect(tickNode, 'onclick', function(e) {
dojo.stopEvent(e);
this.update(this.id, p);
});
}
I would consider looking into dojo.create as well instead of createElement as well. Good luck!
Alternatively, and I think it's cleaner, you can pass the context into dojo.connect as the third parameter:
dojo.connect(tickNode, 'onclick', this, function() {
this.update(this.id, i);
});