I curently develop an app in javascript and I want to use cordova or phonegap to adapt my code to android, Iphone, etc. But in my app I save my file with this function :
function save(){
var myFileJSON = JSON.stringify(myFile);
try{
var blob = new Blob([myFileJSON], {type: "text/plain;charset=utf-8"});
saveAs(blob, "myFileJSON.txt");
} catch (e){
console.log('bug');
}
}
So with my phone application I want to save my file in a specific folder. Can I catch the save event and, for exemple, redirect immediately the path?
function saveCourseToFile() {
console.log("checkpoint 1");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError);
}
function onFSSuccess(fileSystem) {
console.log("checkpoint 2");
console.log("Opened file system: " + fileSystem.name);
fileSystem.root.getFile("readme.txt", {create:true, exclusive:false}, gotFileEntry, onFSError);
}
function gotFileEntry(fileEntry) {
console.log("checkpoint 3");
fileEntry.createWriter(gotFileWriter, onFSError);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("checkpoint 4: write success!");
};
writer.write("test test test");
}
You can also check this link for your reference.
Related
I'm trying to output selected file's path in the DOM by using JS only.
For that I'm using
https://github.com/ihadeed/cordova-filechooser
&
https://github.com/hiddentao/cordova-plugin-filepath
plugins
openFile: function() {
fileChooser.open({ mime: "audio/mpeg" }, app.winCallback, app.failCallback); winCallback: function() {
let actualPath;
let err;
fileChooser.open(function(uri) {
window.FilePath.resolveNativePath(uri, actualPath, err);
alert(actualPath);
}); } , failCallback: function() {
console.log("Couldn't access files"); }
I'm getting the selected file's URI, But I'm unable to understand how to use this with cordova-plugin-filepath.
I'm trying to get a file path something like this
file:///storage/emulated/0/planetes.mp3
The function has to structured in following way. This seems to work on Android 6. The fileChooser plugin didn't work on android 4.4.2.
winCallback: function() {
fileChooser.open(function(uri) {
window.FilePath.resolveNativePath(uri, successNative, failNative);
function failNative(e) {
console.error("Something Went Wrong!");
}
function successNative(finalPath) {
var path = finalPath;
console.log(path);
document.getElementById("audio-file").src = path;
}
}); }
Currently i am working on opening pdf document in angularjs w.r.t. desktop/ mobile also.
i have followed this ref.:
Open a PDF in a new window of the browser with angularjs
there similar implementation i have done :
code is as follows
**$http.get('generatePdfUrl')
.then(function (data) { // data is your url
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});**
even i have applied responsetype : 'arraybuffer' as well,
in the angularjs web application this url points to
blob://http://localhost:8080/126gyesdfsdfadjf,
its is opening pdf document properly with window.open(fileURL),
but the same is not working for the angularjs mobile application using cordova build,
there application url points out to blob:file///126gyesdfsdfadjf,
but unable to open pdf document,
can anybody have suggestions on this.
regars,
vasu.
For this, you need to install a plugin for opening the pdf document.
function writePDFToFile(fileName, data){
try{
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function(directoryEntry){
directoryEntry.getFile(fileName, { create: true }, function(fileEntry){
fileEntry.createWriter(function(fileWriter){
fileWriter.onwriteend = function(e){
cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',{
error: function(e){
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
console.log('file opened successfully');
}
});
};
fileWriter.onerror = function(e){
alert(e);
};
var blob = new Blob([data], { type: 'application/pdf' });
fileWriter.write(blob);
}, function onerror(e){
alert(e);
});
}, function onerror(e){
alert(e);
});
},function onerror(e){
alert(e);
});
}catch(e){
alert(e);
}
}
above implementation worked for me.
Check this link for plugin.
How can I convert a file (png/jpg/word/excel etc) to base64 format if I have url of the file (in the browser's sandboxed LocalFileSystem) which is already there in client system using javascript.
I had tried using creating canvas(image).
I also tried file control.
I don't want to use any control as we have url of the file in the sqllite db.
I tried
function UploadAttachmentfile() {
try {
if(objAttachment.length >0)
{
var ctn = objAttachment.length;
for (var j = 0; j < ctn; j++) {
var row = objAttachment[j].IMGS; \\image
var fname = row.split('\\').pop().split('/').pop();
alert(fname);
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fs) {
alert('request file system');
fs.root.getDirectory("Foldername", null, function (entry) {
alert('ENTRY : '+entry);
entry.getFile(fname, null, function (fileEntry) {
fileEntry.file(gotFile, fail);
}, fail);
}, fail);
}, fail);
function gotFile(file) {
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
alert("Read as data URL");
alert("target result :"+evt.target.result);
};
reader.readAsDataURL(file);
}
function fail(evt) {
alert('fail');
alert(evt.target.error.code);
}
}
}
}
catch (err) {
}
}
But it always alert fail only.
If you want to get the file on the user's computer WITHOUT the user selecting it (EVERY SESSION AGAIN), then, you can not do it (thank <enter deity here>). I highly reccomend to read this answer linked here for a complete and up-to-date explenation.
If however your user selects the file during his session via an file-input enabled element, then it is simple:
Assuming you've got the url using createObjectURL() after the user selected the file(s), then you simply use the file-reader's readAsDataURL( fileObject || local URL ) method:
fileReader.readAsDataURL( fileObject );
That will encode it to base64.
EDIT:
turns out you are developing for mobile phone using Cordova (I've added that tag to your Question). However that's still based on the file-api and has the same .readAsDataURL() method: see documentation here. It contains simple examples and notes on different mobile platforms!
Also, it seems you are trying to get a file from the LocalFileSystem interface of the File System API (that gives you access to the browser's sandboxed file system). So the other answer I linked to doesn't apply (much).
The following example (modified from the documentation linked above) should get you started:
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
From here on, you change the console.log(evt.target.result); part: instead of writing the base64 output to the console, you send that string back to the server (again using AJAX, etc.)
Done :)
I'm currently working on finding out what PhoneGap can/can't do in iPhone app development. So far I have managed to write a file to the LocalFileSystem using FileWriter and on the click of a button reads the file back to the user. I have been asked to find a way to set the app so when the app writes a file, the file is saved to a folder/location specified by the user. I've been looking, but I can't find any information to do with this. Is it even possible to do so? And if so, can you please help me?
(I am using JavaScript, HTML and PhoneGap in Xcode for this app)
Here's the code I used to write/read the file using the LocalFileSystem;
var reader;
var text;
var myFileSystem;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function myfile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotmyFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
myFileSystem = fileSystem;
console.log(fileSystem.name);
}
function gotmyFS(fileSystem) {
fileSystem.root.getFile("readme2.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
fileEntry.file(gotFile, fail);
}
function gotFileWriter(writer) {
writer.write("some sample text");
}
function gotFile(file){
readAsText(file);
}
function readDataUrl(file) {
reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
console.log(file);
text = evt.target.result;
};
reader.readAsText(file);
}
function readmyfile() {
var myPara = document.getElementById("mytext");
myPara.innerText = text;
}
function fail(error) {
console.log(error.code);
}
This all works, but is there something i should add/remove to make it work?
Thanks a lot in advance xx
iOS apps are sandboxed and you can write only to specific directories. more details here.
im trying to get the default music folders for all phonegap supported platforms. basically i can download and save file on the sdcard using the function below. but i want to add code to detect platform and give me default music folders for platform so as i can save mp3 file there.
function downloadFile(remoteloc,new_name,userid,mid,errorbox,origname)
{
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html","");
var fileTransfer = new FileTransfer();
fileEntry.remove();
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"progress progress-danger progress-striped\"><div id='id_p' class=\"bar\" style=\"width: 5%\"></div></div>");
fileTransfer.onprogress = function(progressEvent)
{
if (progressEvent.lengthComputable) {
$('#id_p').css('width',Math.ceil((progressEvent.loaded / progressEvent.total)*100)+"%");
} else {
}
}
fileTransfer.download(
remoteloc,
sPath + new_name,
function(theFile) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-info fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Complete. Added to Media Player</div>"
+"<div>Play Song</div>"+"<br/>"+theFile.toURI());
//update the database field to show file has been transfered
if (!isOnline())
{
$('#error_box').html("<div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Sorry but you seem to be offline.</div>");
return;
}
var request={'controller':'music','action':'updatedownload','userid':userid,'mid':mid};
queryAPI(request,function (d){
//check result and set local storage variables
if (d.success>0)
{
} else
{
}
localStorage.removeItem('resume');
window.key=false;
//setTimeout(function () {$('#'+errorbox).html("<div>"+origname+"</div>");},3000);
});
},
function(error) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Error! Error code:"+error.code+"</div>");
}
);
},
fail);
},
fail);
}
Because of major platform differences, there isn't a "one time getDirectory call" solution to do this.
The best way to handle this is to do a check for the platform you're currently running and write the file based on that.
var platform = device.platform;
switch(platform)
{
case 'iPhone':
//save to the app document folder
break;
case 'Android':
//save to <external_storage_root>/Music
break;
case 'BlackBerry':
//Save to /SDCard/BlackBerry
break;
}
Be sure to check official documentation for the right file path's etc.
Also take note that while /var/root/Media/iTunes_Control/Music is sometimes mentioned as the default folder for music on iOS, it's managed by iTunes so it can be modified at any time and is only useful for temporary storage if it can be accessed at all. Using the documents folder is the prefered method.