i use this code to download an apk from my localhost
function downloadApkAndroid(data) {
var fileURL = "cdvfile://localhost/persistent/path/to/Download/";
var fileTransfer = new FileTransfer();
var uri = encodeURI(data);
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("download complete: " + entry.fullPath);
promptForUpdateAndroid(entry);
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
}
);
}
i got success to donwload then it will call this function promptForUpdateAndroid(entry); to try install it which the function contain this
function promptForUpdateAndroid(entry) {
console.log(entry);
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
url: entry.toURL(),
type: 'application/vnd.android.package-archive'
},
function () {
},
function () {
alert('Failed to open URL via Android Intent.');
console.log("Failed to open URL via Android Intent. URL: " + entry.fullPath);
}
);
}
after it call that function i got alert
Parse error - there was a problem parsing the package
what i think is the fileURL var fileURL = "cdvfile://localhost/persistent/path/to/Download/"; is wrong but i dont really know what is actually the path is. please help me
ok i fix my problem already. i put in here incase someone got same problem. its true that path i put is wrong actually because i got the apk i download form server but cant install it becaue it didnt have permission since it puth at the root user so i change the path to
var fileURL = cordova.file.externalDataDirectory+'android.apk'
then after it successfully download the file web intent will automatically prompt user to install or not.
Related
I am downloading a file from the server, it returns in Blob format. I have used the following piece of code to convert blob to URL.
const blob = new Blob([data], { type: 'application/pdf' });
const url= window.URL.createObjectURL(blob);
After that, I have used Cordova-File-Transfer-Plugin code to Download that File. Code provided below:
downloadOverMobile(url){
var fileTransfer = new FileTransfer();
let fileURL = 'cdvfile://localhost/persistent/Download/Invoice.pdf';
var uri = encodeURI(url);
fileTransfer.download(uri,fileURL,
function(entry) {
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code " + error.code);
},
false,
{
headers: {
}
}
);
}
I am getting the following response:
download error source blob:file:///d1339351-7d29-4dcd-bba6-0b037003c886
download error target
cdvfile://localhost/persistent/Download/Invoice.pdf
download error code 2
I am using angular 4 and Cordova 8.1.2. Can Anyone tell me what am I missing?
I have uploaded vcf file successfully on server on getting help from my previous question (the one which is edited)
Now I need a help in how to read that vcf file or vcard from server and display as a contact number and contact name in my phonegap app.
plugin used cordova-plugin-file-transfer
Can anyone help on this ?
Using plugin cordova-plugin-file-transfer https://github.com/apache/cordova-plugin-file-transfer you can download file from server.
For Read vcf file, you need https://github.com/nilclass/vcardjs JavaScript based library. you can directly use .js files.
You can follow below example.
window.requestFileSystem(window.TEMPORARY, 1 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
var fileName = "temp.vcf";
var dirEntry = fs.root;
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
download(fileEntry,"server-path-to-file.vcf");
}, onErrorCreateFile);
}, onErrorLoadFs);
function download(fileEntry, uri) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("Successful download...");
console.log("download complete: " + entry.toURL());
readFile(entry);
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log("Successful file read: " + reader.result);
reader.parseVCard(reader.result);
};
reader.readAsText(file);
}, onErrorReadFile);
}
function parseVCard(vCarddata){
VCF.parse(vCarddata, function(vcard) {
// this function is called with a VCard instance.
// If the input contains more than one vCard, it is called multiple times.
console.log("Formatted name", vcard.fn);
console.log("Names", JSON.stringify(vcard.n));
});
//Fore more help:https://github.com/nilclass/vcardjs
}
I'm trying to save a file, that exists on my server and displays in my app, to download and save to the client's file system. What's the best way to do this in meteor?
My current implementation is using the window.requestFileSystem and FileTransfer (Which I believe is a cordova plugin)
I've also tried LocalFileSystem.PERSISTANT, but then I get an undefined error.
The code:
var fileSystem;
//step one is to request a file system
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0,
function(fs) {
fileSystem = fs;
console.log(fileSystem);
var fileTransfer = new FileTransfer();
var uri = encodeURI(imageBaseUrl + origUri);
fileTransfer.download(
uri,
fileSystem.root.fullPath + 'download.pdf',
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log(error);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}, function(e) {
alert('failed to get fs');
alert(JSON.stringify(e));
});
The errors I'm getting on Android is as follows:
FileSystem object:
name: "temporary"
root: DirectoryEntry
filesystem: FileSystem
fullPath: "/"
isDirectory: true
isFile: false
name: ""
nativeURL: "file:///storage/emulated/0/Android/data/com.myapp.app/cache/"
FileTransferError object:
body: null
code: 1
exception: "/download.pdf: open failed: EROFS (Read-only file system)"
http_status: 200
source: "http://example.com/upload_H5XtiJJRf2Bmeq3d.pdf"
target: "/download.pdf"
Thing is, in the AndroidManifest.xml, permission is requested for EXTERNAL_WRITE_ACCESS, so surely the filesystem should be writable then?
Is there some other permission that needs to be granted, and if so, where and how do I request it?
Thanks!
I'm having problems with the Phonegap FileTransfer API. Currently I'm trying to run the example code below:
saveFile: function (filepath,location, filetype) {
console.log("FUNCTION BEING CALLED");
var self = this;
//filepath is path to the internets file
//location is where on the device the file will be stored
var fileTransfer = new FileTransfer();
fileTransfer.download(filepath,self.rootPath + location + '.' + filetype,
function (entry) {
console.log('############# DOWNLOAD WORKS ##############');
console.log("download complete: " + entry.fullPath);
},
function (error) {
console.log('############# DOWNLOAD FAILS ##############');
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
)
}
Currently, nothing at all appears to be happening. No errors are flagged, and the callbacks don't appear to be firing. All I get is the initial console.log of "FUNCTION BEING CALLED".
I've double checked, and can confirm that I'm including the cordova js file, (cordova-2.4.0.js).
If it matters, I've tried this on the Android Emulator, a HTC One X and a Samsung Galaxy S3, all with the same results.
Does anyone know what could be causing this?
Edit: I also felt I should mention that it's all running in an Angular JS app as well.
this is how i am doing it in my project
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
window.fileSystem = fileSystem;
//create directory test_app
fileSystem.root.getDirectory("test_app", {
create : true,
exclusive : false
}, dirWallpaper, fail);
function fail(evt) {
}
function dirWallpaper(entry) {
//save the directory path
window.testDir = entry;
}
//now download file to that location
saveFile: function (filepath,location, filetype) {
console.log("FUNCTION BEING CALLED");
var self = this;
//filepath is path to the internets file
//location is where on the device the file will be stored
var fileTransfer = new FileTransfer();
var path = window.testDir.fullPath + "/test_pdf."+ filetype;
fileTransfer.download(filepath,path,
function (entry) {
console.log('############# DOWNLOAD WORKS ##############');
console.log("download complete: " + entry.fullPath);
},
function (error) {
console.log('############# DOWNLOAD FAILS ##############');
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
)
}
try like this and let me know.
I wrote an jQuery Mobile app and packaged it with Phonegap to iOS and Android apps.
At this point I am using locally stored json files to read data.
I would like to update these json files from time to time by downloading newer json files from a server.
How can I get the json from the server and store the json files to the local file system of Android and iOS?
Cheers
Johe
Use FileTransfer.download, here is an example:
function downloadFile(){
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();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);
};
}
This is how I solved it. First set the file paths, wich are different for Android and iOS
var file_path;
function setFilePath() {
if(detectAndroid()) {
file_path = "file:///android_asset/www/res/db/";
//4 Android
} else {
file_path = "res//db//";
//4 apache//iOS/desktop
}
}
Then I load my JSON files, wich are prepackaged with the app, into the local browser storage. Like this:
localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");
function loadJSON(url) {
return jQuery.ajax({
url : url,
async : false,
dataType : 'json'
}).responseText;
}
If I wanna update my data. I get the new JSON Data from the server and push it into the local storage. If the server is on a different domain, which is the case most of the time, you have to make a JSONP call (check jQuery's docs on JSONP).
I did it kinda like this:
$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
//write to local storage
localStorage["my_json_data"] = JSON.stringify(json_data);
});
You can do this in one line of code:
new FileManager().download_file('http://url','target_path',Log('downloaded success'));
target_path: can include directory (example: dira/dirb/file.html) and the directories will be created recursively.
You can find the library to do this here:
https://github.com/torrmal/cordova-simplefilemanagement
My suggestion would be to look into PhoneGap's File API. I haven't used it myself, but it should do what you're after.
Updated Answer for new Cordova
function downloadFile(url, filename, callback, callback_error) {
var fileTransfer = new FileTransfer();
fileTransfer.download(url,
cordova.file.dataDirectory + "cache/" + filename,
function (theFile) {
console.log("download complete: " + theFile.toURL());
if (callback)
callback();
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
if (callback_error)
callback_error();
}
);
}
For downloading and displaying a file, follow the sample code.
Include the given code just above the </head> tag in your index.html
< script type = "text/javascript" charset = "utf-8" >
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
alert("Going to start download");
downloadFile();
}
function downloadFile() {
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();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
},
fail);
},
fail);
}
function showLink(url) {
alert(url);
var divEl = document.getElementById("deviceready");
var aElem = document.createElement("a");
aElem.setAttribute("target", "_blank");
aElem.setAttribute("href", url);
aElem.appendChild(document.createTextNode("Ready! Click To Open."))
divEl.appendChild(aElem);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
Refer :- Blog Post