I've been running through docs and everything for the past couple of hours but with no success...
I want to download a file from some server and to save it on my phone (the directory where the app stores files that are only visible to my app and are deleted when the app is uninstalled). I would like to store a file and write to it (I've done the download part). With the following code, when I run it, it works and display the text from the "file" but when I search for the file using some file explorer apps, the file that I've "created" is nowhere near to be found.
Cheers!
EDIT Notes:
Okay so I've now even tried to create a file on my phone from the computer using a usb connection so I know for a fact the the file exists...
The path of the file where I created it from the pc is:
This PC\Galaxy S7 edge\Phone\Android\data\com.phonegap.musicapp2\text.txt
The response code that I get from JSON.stringify(dirEntry) is the following
{"isFile":false,"isDirectory":true,"name":"com.phonegap.musicapp2","fillPath":"/data/user/0/com.phonegap.musicapp2/", "filesystem":"","nativeURL":"file:///data/user/0/com.phonegap.musiapp2/"}
So when I run the code from bellow, it gives me
Error from getFile: {"code":1}
I've looked through the docs and it says that code 1 mean: NOT_FOUND_ERR (http://prntscr.com/n071kx)
"Code from bellow"
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
DebugConsole.log("Successful file read: " + this.result);
// displayFileData(fileEntry.fullPath + ": " + this.result);
};
reader.readAsText(file);
}, onErrorReadFile);
}
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory, function(dirEntry) {
DebugConsole.log(JSON.stringify(dirEntry));
dirEntry.getFile('text.txt', {create: false, exclusive: false}, function(fileEntry) {
//writeFile(fileEntry, null, isAppend);
readFile(fileEntry);
}, function(e) {
DebugConsole.log('Error from getFile: ' + JSON.stringify(e));
});
});
Sidenote:
App never asks for permission to access my internal storage.
I went into Apps/myapp/permissions and it showed that the app doesn't have permission to access the storage. I turned it on but still no luck.
I think I need to somehow request storage access from the app but I can't seem to find a way how?
I managed to find a solution with the following
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory + "Android/data/app.name/files/", success, fail);
Related
I can get an SVG file downloaded, additionally, I can display svg files as you would normally within an image tag. I do not know how to access the folder location for downloads or the wgt-private folder so I may download images to a client's watch and then use the downloaded version.
I'm sure my file is downloading as I've console logged on successful download and when I list the items in the directory the file shows up.
Placing downloads/[filename] or wgt-private/[filename] does not appear to work as these are virtual file locations however I've no idea how to access these files within the application without using the filesystem methods.
Download:
var download_obj = new tizen.DownloadRequest('someFile.svg', 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
onprogress: function(id, receivedSize, totalSize) {
console.log(id);
console.log(receivedSize);
console.log(totalSize);
},
onpaused: function(id) {
console.log(id);
},
oncanceled: function(id) {
console.log(id);
},
oncompleted: function(id, fullPath) {
console.log(id);
console.log(fullPath);
},
onfailed: function(id, error) {
console.log(id);
console.log(JSON.stringify(error));
}
});
Full path comes out as: wgt-private/someFile.svg
Doesn't display as displays a file error in the console on all attempts.
I understand that your questions relates to how to show the image downloaded with tizen.download API in html img tag.
I can see two workarounds that could help you with it:
You can use filesystem API (which you would like to avoid), BUT since 5.0 there is a method which needs no additional privileges and I hope it will match your needs - FileSystemManager.toURI(). It just gets the path to file (returned by download API) and returns the full URI, able to be used in img.
I noticed that download to non-public directories on the device, download API returns the 'hidden' path which uses virtual root, but when downloading to public directory as 'downloads', the full path is returned and it works for img as well.
If both of above is not acceptable for you, I am afraid that the only alternative is to use regular tizen.filesystem API and resolve the path from download API and then use File.toURI() function to get the path.
var link = "http://techslides.com/demos/samples/sample.jpg"
var download_obj = new tizen.DownloadRequest(link, 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
oncompleted: function(id, fullPath) {
console.log("completed " + id + " : " + fullPath);
tizen.filesystem.resolve(fullPath, (s)=>{console.log("Resovled full path: " + s.toURI())}, (e) => {console.log(e)})
},
onfailed: function(id, error) {
console.log("failed " + id);
console.log(JSON.stringify(error));
}
});
You can find the proper web sample app: new Tizen project - Sample - Mobile 4.0 - Web application - Content - Download Manager
Open index.html and replace https://www.sample-videos.com/video/mkv/720/big_buck_bunny_720p_10mb.mkv with your file address.
I'm trying to use Meteor 1.4 with Cordova (mobile support) to read files on my android phone.
I've got a small Meteor app running on my phone (via meteor run android-device). I have also created a small text file in the app's private storage using adb shell and run-as.
I can read the file if I call getFile('a'), but I can't find any way to use cordova.file.dataDirectory (even with WebAppLocalServer.localFileSystemUrl) as recommended in the Meteor guide. I get FileError {code: 5} (ENCODING_ERR).
Here's the JS console output from the Chrome inspector when I click the button in my app:
This repros on both Android 5 and 6.
My dev environment is 64-bit Ubuntu 14.04 LTS.
App Info for my app reports it has these permissions:
modify or delete the contents of your SD card
read the contents of your SD card
The app uses the cordova file plugin version 4.2.0.
Dup? How to read/write a file in Meteor-Cordova?
This does work in the chrome://inspect console via USB debugging: HTTP.call('GET', 'http://localhost:12640/local-filesystem/data/user/0/com.adammonsen.app/files/a', {}, function (e,r) {console.error(e); console.log(r)});
output is Object {statusCode: 200, content: "in external dir↵", headers: Object, data: null}
Got it. The trick is to use window.resolveLocalFileSystemURL() to get at the filesystem. Here's how to get at a file on external storage. My original question was about app-private storage. If you're looking for that, just use the cordova.file.dataDirectory instead of cordova.file.externalDataDirectory.
function reportError(err) {
console.error(err);
}
function readFile(file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log('read file! contents: ' + this.result);
};
reader.readAsText(file);
}
function processFileEntry(fileEntry) {
fileEntry.file(file => {
readFile(file);
}, reportError);
}
Template.hello.events({
'click button'(event, instance) {
// increment the counter when button is clicked
instance.counter.set(instance.counter.get() + 1);
if (Meteor.isCordova) {
// aaaaaand do some other stuff
const path = cordova.file.externalDataDirectory + 'a';
window.resolveLocalFileSystemURL(path, fileEntry => {
console.log('fileEntry: ', fileEntry);
processFileEntry(fileEntry);
}, reportError);
}
},
});
See https://github.com/meonkeys/cordova-file-test/tree/solution for a full working example and instructions.
Make sure AndroidExtraFilesystems includes files-external. I used this line in my mobile-config.js:
App.setPreference('AndroidExtraFilesystems', 'files,files-external');
I'd love to understand the difference between the APIs, but for now I'm just happy I found something that works reliably.
I am working on a completely locally run web app which is to be run without any network connection. The idea is to distribute a pack to users (~40) who will use the app to basically fill in bunch of form fields and charts. As changes are made to the page an object with data in JSON format is filled in. I have the page working well now and I have a function to load an existing JSON file and populate any fields that are present in the file. The idea behind this is that someone can be "halfway" through filling out the fields in the app or someone can load up previous work.
My question here is; what is the best system available to get data from a webpage into JSON file and be able to save that to local machine so that it can be distributed (emailed, saved to SP, network drive, access db etc etc) at a later date? The scenario under which the app will be used is a strictly no network access area so this is why I need to be able save and access a file locally. I have a half-solution where I can open a separate tab which has the contents of the file but I really would prefer to have the downloading/saving prompting done for me as most users won't go further than seeing a page with gibberish on it.
the code I have to accomplish this much is:
//Download file
function SaveToDisk() {
var data = JSON.stringify(currentSession);
var fileURL = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
var fileName = $('file-save').val();
console.log(fileURL);
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
currentSession object looks like:
//Global JSON variables
var currentSession = {
"sections":{
"header":{
"tool":"",
"subsystem":"",
"engineer":"",
"date":"",
"so":""
},
"whys":{
"why1":{
"error":"",
object:"",
norm:"",
},
why2:{
error:"",
object:"",
norm:"",
},
why3:{
error:"",
object:"",
norm:"",
},
why4:{
error:"",
object:"",
norm:"",
},
why5:{
error:"",
object:"",
norm:"",
}
},
probDescription:{
"F":{
"is":"",
"isnot":""
},
"O":{
"is":"",
"isnot":""
},
"T":{
"is":"",
"isnot":""
},
"L":{
"is":"",
"isnot":""
},
"P":"",
"W":"",
"Pos":"",
"S":""
},
possibleCauses :{
"data":""
},
notes: ""
}
};
UPDATE: Attempting this on windows machine (up to now been testing on mac) on IE9 gives the following error:
SCRIPT5007: Unable to get value of the property 'document': object is null or undefined
at the following line of the above code:
_window.document.close();
Checking up on the line before:
// for IE
else if ( !! window.ActiveXObject && document.execCommand) {
shows me that the if statement checks if activeXObject is present (only in IE???) and something else (div editable???) is true then it goes with the IE solution.
Then it creates a new window with the data url, (not sure what '_blank' is here) and attempts to save the file. So why is it erroring on the _window.document line? It does open a new window with the URL as:
data:application/octet-stream;{data}
Any help here also greatly appreciated(and needed)
All help and suggestions gladly welcomed as I am rather new to all this and still learning.
Thx in advance
To force the download/saving prompt you can change the MIME type to application/octet-stream. The MIME type won't be saved to disk, so you don't have to worry about that later on. The second line in the function should therefore read:
var fileURL = 'data:application/octetstream;charset=utf8,' + encodeURIComponent(data);
Of course there are good reasons that this local saving procedure can not be completely automated. Otherwise viruses could be easily distributed.
If you want to access the file later to distribute it via email, the local storage solutions in html5 do not really help.
Since I work mostly on IE9 and can guarantee that the users will use this I found this answer solved my issue:
https://stackoverflow.com/a/6106417/1770604
I have it implemented like so:
//Make file for attaching to mail
function makefile () {
var fso = new ActiveXObject("Scripting.FileSystemObject"),
FName = $('#file-save').val() + ".json",
data = JSON.stringify(currentSession),
thefile=fso.CreateTextFile("C:\\temp\\" + FName,true);
thefile.Write(data);
thefile.Close();
alert("File created and saved to C:/temp/directory");
}
I have searched as much as possible and to my limited knowledge there are only two solutions to this without using a separate server:
ActiveXObject in IE9 which allows the user to interact with the file system and write to a file in a specified dir - from what i've read this is not a very secure solution however this is my only real option.
Some form of local/portable web server which can be distributed and started without user needing to do anything - I haven't been able to find the answer to this question yet so will keep looking but consider the question answered for now as long as you use IE9.
In my cordova(v 3.3) application i used copyTo for copy files from one directory to another directory in sdcard. Some time it is working fine some time it is not working.
Here is the source i used to copy files from one dierctory to another.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function gotFS(fileSystem) {
var root = fileSystem.root.fullPath;
console.log(skiTemplateFileName);
alert(root);
var fails = function(err) { alert(err.code);}
window.resolveLocalFileSystemURI(root+"/"+TEMPLATE_DIRECTORY+""+TemplateFileName, function(file) {
window.resolveLocalFileSystemURI(root+"/"+PDF_DIRECTORY, function(destination) {
file.copyTo(destination,randomFileName);
alert("File Download Successfully");
},fails)
},fails);
}, function fail(e){
});
when copy files first time only shows the file download success. For next time it shows only root alert
Note : This issue occurs in samsung tab 4(v4.4.2) devices working well in nexus 7.
Please guide to solve this issue.
In order to send one file from my android device's File System to one server, I am using cordova 3.5 and the following code (as you can get reading this code the file is inside my Download directory):
receivedEvent: function(id) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fail);
}
function fsSuccess(fs){
fs.root.getDirectory("Download", {create: false, exclusive: false}, doDirectoryListing, FileError);
}
function doDirectoryListing(dirEntry) {
var directoryReader = dirEntry.createReader();
directoryReader.readEntries(gotFiles, FileError);
}
function gotFiles(entries)
{
var wsUrl = "http://myServer/";
var fileToSend = "file:///storage/sdcard0/Download/"+entries[0].name, "file:///storage/sdcard0/Download/";
multipart.uploadFiles(success, error, wsUrl, fileToSend);
}
I can read all the files (names) that are in /Download parsing all the entries but I dont know how to get a specific file (for instance entries[0]) which needs to be passed to uploadFiles function.
Problem: I tried in different manner as for instance concatenating it with "file:///storage/sdcard0/Download/" but always getting a file not found exception.
I found the solution on my own,
mainly file:// is to be removed.
It could be gained this way: fileToSend.replace("file://", ""));