I am using below code to write a file on android using PhoneGap, I think that this line window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { is giving the error, can't find the exact error, just because I can't debug on android.
I find PhoneGap documentation confusing.
function download_file(cur_filename)
{
alert(5);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
alert(2);
console.log('file system open: ' + fs.name);
alert(3);
fs.root.getFile(cur_filename, { create: true, exclusive: false }, function (fileEntry) {
alert("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
fileEntry.name==cur_filename;
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function writeFile(fileEntry, dataObj) {
aler(4);
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['some file data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
Firstly, you can directly download the file rather than having to create and write a new one. You need to first install the following plugins
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
Now, you need to enclose the below logic inside deviceready event in case you are accessing plugins on app launch. The file-transfer ships with a download() that you need to use for downloading your file. Please find a sample code below
document.addEventListener("deviceready", startDownload, false);
function startDownload() {
var fileTransfer = new FileTransfer();
// replace uri with -> http://192.168.43.54/text.csv
var uri = encodeURI("https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4");
fileTransfer.download(
uri,
cordova.file.dataDirectory + 'videos/big_buck_bunny_720p_1mb.mp4',
function(entry) {
console.log("download complete: ", entry);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Once the download is completed, the entry object will have a nativeURL property that holds the local URL to the file.
More info
File Plugin
File-Transfer Download
Related
I am using the "Cordova Audio Recorder API Plugin" in my app its working great,but i am unable find the recorded file,In plugin they say it is stored in
"iOS: /var/mobile/Applications//Library/NoCloud/.m4a"
"Android: /data/data//files/.m4a"
I am unable to get it,even i try to change the directory but still no luck below is code which i change the directory.Need help
window.plugins.audioRecorderAPI.record(function(savedFilePath) {
var fileName = savedFilePath.split('/')[savedFilePath.split('/').length - 1];
var directory;
if (cordova.file.documentsDirectory) {
directory = cordova.file.documentsDirectory; // for iOS
} else {
directory = cordova.file.externalRootDirectory; // for Android
}
$cordovaFile.copyFile(
cordova.file.dataDirectory, fileName,
directory, "new_file.m4a"
)
.then(function (success) {
alert(JSON.stringify(success));
}, function (error) {
alert(JSON.stringify(error));
});
}, function(msg) {
alert('ko: ' + msg);
}, 3);
In my nativescript app, I'm able to record a video, but I want to upload it to an S3 bucket for later streaming. I'm running a node js server that handles the api for my app.
I'm trying to use the 'nativescript-background-http' library, but it always breaks when I try to run the uploadFile function.
Here's the relevant code:
var uploadVideo = function (filepath) {
console.log("Attempting to upload video...");
var session = bghttp.session("video-upload");
var filename = filepath.replace(/^.*[\\\/]/, '');
var request = {
url: config.apiUrl + 'upload',
method: "POST",
headers: {
"Content-Type": "video/mp4",
"File-Name": filename
},
description: "{ 'uploading': filename }"
};
try {
var task = session.uploadFile(filepath, request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log("Logging event.");
console.dir(e);
console.log(e.eventName);
}
}
catch (error) {
console.dir(error);
console.log("An error occurred uploading the file. Removing video from filesystem...");
var documents = fs.knownFolders.documents();
var file = documents.getFile(filename);
file.remove()
.then(function (result) {
console.log("The video has been removed successfully.");
}, function (error) {
console.log("The video could not be removed from the file system.");
console.dir(error);
});
}
};
This is the output I end up with:
JS: Video located at /data/user/0/org.nativescript.Lifey/files/videoCapture_1486072596043.mp4
JS: Attempting to upload video...
JS: === dump(): dumping members ===
JS: {
JS: "nativeException": {
JS: "constructor": "constructor()function () { [native code] }"
JS: }
JS: }
JS: === dump(): dumping function and properties names ===
JS: === dump(): finished ===
JS: An error occurred uploading the file. Removing video from filesystem...
JS: The video has been removed successfully.
Any idea what's going on? Does 'nativescript-background-http' library even support video uploads (I've only seen image upload examples on their github)? Is there some alternative that I could use if I can't use that library?
In Chrome Apps, I'm downloading a blob content from a server using JavaScript XHR (Angular $http GET in particular, with response type 'blob')
How should I save this to chrome application's file system?
Currently using an Angular wrapper on HTML5 filesystem API
https://github.com/maciel310/angular-filesystem
I do not want to show user a popup (hence I can't use chrome.fileSystem. chooseEntry )
The chrome.fileSystem.requestFileSystem API is only supported by Kiosk-only apps.
Hence I'm using HTML5 FileSystem API instead of chrome's.
I'm using following code to make XHR to fetch blob.
$http({
url: SERVER_URL+"/someVideo.mp4",
method: "GET",
responseType: "blob"
}).then(function(response) {
console.log(response);
fileSystem.writeBlob(response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
}, function (response) {
});
This is my writeBlob method
writeBlob: function(fileName, blob, append) {
append = (typeof append == 'undefined' ? false : append);
var def = $q.defer();
fsDefer.promise.then(function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
if(append) {
fileWriter.seek(fileWriter.length);
}
var truncated = false;
fileWriter.onwriteend = function(e) {
//truncate all data after current position
if (!truncated) {
truncated = true;
this.truncate(this.position);
return;
}
safeResolve(def, "");
};
fileWriter.onerror = function(e) {
safeReject(def, {text: 'Write failed', obj: e});
};
fileWriter.write(blob);
}, function(e) {
safeReject(def, {text: "Error creating file", obj: e});
});
}, function(e) {
safeReject(def, {text: "Error getting file", obj: e});
});
}, function(err) {
def.reject(err);
});
return def.promise;
},
This shows SECURITY_ERR as It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.
What's the solution for this?
I've tried using --allow-file-access-from-files flag while launching app. It doesn't help.
Chrome Application's sandbox storage doesn't allow files to be stored in root directory (i.e. / )
Modify the code to save it in a specific sub-directory under it.
For example -
fileSystem.writeBlob("/new"+response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
This would successfully save the file under /new/ directory.
To expand on this, here is a full example app on how to download a file and save the blob and display it back to the user.
https://github.com/PierBover/chrome-os-app-download-example
I want to deleate a file in phonegap android application.
file is exists in subfolder.
I am finding a sample code on the internet.But I can't see.
Phonegap docs
is not enough for me.Can someone answer me how to delete a file within a subfolder.
function deleteFilelists(tx,results)
{
var fileName = "cdvfile://localhost/persistent//flower.jpg"
removefile(fileName);
function removefile(fileName){
fileSystem.root.getFile(fileName, {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
fileEntry.remove(success, fail);
}
function success(entry) {
alert("Removal succeeded");
}
function fail(error) {
alert("Error removing file: " + error.code);
}
}
I am trying to save multiple files to a directory - in one operation. If I correctly understand the chrome fileSystem api documentation this should be possible when I use the openDirectory option for chrome.fileSystem.chooseEntry. Is that even allowed?
However, the documentation is very minimalistic and I also did not find any examples via google.
More background:
I have the proper permissions to access a directory and also have write permissions:
/*you need chrome >= Version 31.x [currently chrome beta]*/
"permissions": [
{"fileSystem": ["write", "directory"]}, "storage",
]
Then you are left with chrome.fileSystem.chooseEntry(object options, function callback) and chrome.fileSystem.getWritableEntry(entry entry, function callback), but I did not figure out if these functions are even what I want.
Here is how a single file can be saved to the file system:
chrome.fileSystem.chooseEntry({type:"saveFile", suggestedName:"image.jpg"},
function(entry, array){
save(entry, blob); /*the blob was provided earlier*/
}
);
function save(fileEntry, content) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
fileWriter.onwriteend = null;
fileWriter.truncate(content.size);
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
var blob = new Blob([content], {'type': 'image/jpeg'});
fileWriter.write(blob);
}, errorHandler);
}
But how can I save multiple files when I use chrome.fileSystem.chooseEntry({type:"openDirectory",..} or does openDirectory only grant me read-rights?
I believe this should work.
chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) {
chrome.fileSystem.getWritableEntry(entry, function(entry) {
entry.getFile('file1.txt', {create:true}, function(entry) {
entry.createWriter(function(writer) {
writer.write(new Blob(['Lorem'], {type: 'text/plain'}));
});
});
entry.getFile('file2.txt', {create:true}, function(entry) {
entry.createWriter(function(writer) {
writer.write(new Blob(['Ipsum'], {type: 'text/plain'}));
});
});
});
});