How to use FileTransfer.download on Android - android

I use Phonegap 1.9.0 on Android, but there are few samples on the web, so I worry about download of a file.
var ft = new FileTransfer();
ft.download(
"http://www.something.com/test.zip",
"test.zip", // <- Trouble 1
function(entry) {
alert("success");
},
function(err) {
alert(err); // <- Trouble 2
}
);
1.I don't understand the way of specifying a file path suitable for this argument. How should I specify a local path? Or is there any required Android.permission?
2.The message "Class not found" is shown. What is this cause?
3.What is the path in native Java of the downloaded file?

Yeah the Cordova/Phonegap docs are very lite on real world examples!
Simon Mac Donald has a great post on downloading: http://simonmacdonald.blogspot.co.uk/2012/04/sorry-for-being-gone-so-long-vacation.html
If you want to download multiple files, check out his gist: https://gist.github.com/3835045
I think FileTransfer is only available on the device (maybe the emulator?), but I also get this error in the browser - maybe someone else can chip in with an explanation/workaround for this one.
This will depend on the platform, but it can be found with FileSystem.root.fullPath. If you are appending filenames, you'll need to add a slash.

// This worked for me
var ft = new FileTransfer();
ft.download(
"http://www.something.com/test.zip", // what u download
"/sdcard/test.zip", // this is the filename as well complete url
// fileSystem.root.toURL() + "test.zip", use ios and others
function(entry) {
alert("success");
alert(JSON.stringify(entry));
},
function(err) {
alert(err);
alert(JSON.stringify(err));
}
);
You can check directory structure in ADT Eclipse DDMS Perspective -> File Explorer

var ft = new FileTransfer();
ft.download(
"http://www.something.com/test.zip", // what u download
"", // this is dir which u download, right now, it will download to mnt/sdcard/
function(entry) {
alert("success");
},
function(err) {
alert(err);
}
);

Related

Cordova/Phonegap File Transfer plugin

I'm using Cordova/Phonegap and I want to use a plugin for download a file and put it in Downloads folder. I find the plugin FileTransfer
http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileTransfer
I'm using this plugin but I don't known the path of folder Download in every device another i want to use the native notification of device...I read that I download the file from remote server but I don't where is and don't show the native console...this is my code in my controller
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://someUrl/tost.pdf");
var fileURL = "/sdcard/Download/tost.pdf";
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("upload error code" + error.code);
},
false,
{
headers: {
//"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
Do you know how I can use it with the native notification and the correct path where I must download it?
If you look at the apache/cordova-plugin-file github you can see the locations where you can read from and write to listed in tables for iOS, Android and Blackberry 10.
From the looks of it you are trying to download to a sdcard on Android? The correct url would look like this:
var fileURL = cordova.file.externalRootDirectory+"Download/tost.pdf";
I'm guessing you want to develop you app for iOS and Android, so you should use this url:
var fileURL = cordova.file.dataDirectory+"Download/tost.pdf";
since it's a valid url on both and it's persistent and private.

FileTransfer only partially download files

Tried to download file using Filetransfer Cordova for android but all the files are downloaded partially. It will download just a random number of Bytes (~ 1-1.5 MB) and then fire a success download event.
This is the code:
var uri = encodeURI('http://192.168.1.5:3000/downloads/' + $scope.file.filename);
var trustHost = true;
var options = {};
var fileName = "thisIsAFile.ext";
$ionicPlatform.ready(function () {})
.then(function(){
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri,
"file://mnt/sdcard/Download/" + fileName,
function(entry) {
$ionicPopup.alert({
title: "success".toUpperCase(),
template: JSON.stringify(entry)
})
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
},
trustHost, options);
});
I can easily download files with a browser from the server (either web or mobile version).
The logcat doesn't help or the success object inspection.
All the permissions are set in res/xml/config.xml and everything looks fine in AndroidManifest.xml
I've also tried different file paths and I've tried with cordova.file.* and fileSystem.root
I'm baffled.
I'm using Ionic and ngCordova.
The FileTransfer is file-transfer 0.4.3
I've tried the 0.5 version and it gives me a persistent code 3 error.
Any suggestions?
I've solved this issue by using the res.sendFile() - i'm using node.js - on server-side. I'm not sure why but it seems that the static url - the resource address - need also a response containing the file data.
I hope this could be helpful.

Local file phonegap with online building app

I'm new to phonegap and I need to know where to put files in a local folder and how to access them. I tried to build my app in my computer with eclipse and so on, but there is too much stuff to install, user variables, command lines ... I tried but it doesn't work and I don't know where is the problem, then I tried to build my app from build.phonegap.com and it worked perfectly. The problem I have is that I need to read an audio file, I tried the Audio object, and the Media object, but they don't work.
I looked for the solution and I found that you have to put your local files in assets/ or android_assets/ and you need to access them, I don't know how
/assets/file.wav
file:///android_assets/file.wav
so I started adding folders like assets/, android_assets/, audios/, whatever/ but nothing works.
can you please tell me where to put my files and how to access them. no command lines, no eclipse... just manually before building the app from build.phonegap.com
Here is a useful link, that maybe helps: link
Have you installed the file plugin? Because this is necessary for it. If not, first of all you need to install it, type in the command line in the project's folder this command (it isn't hard):
cordova plugin add org.apache.cordova.file
According to the file plugin documentation, the best place is to store files is the following path:
file:///data/data/{app-id}/files/files/{your folder}/{your files}
For example: file:///data/data/com.phonegap.myapp/files/files/audio/file.wav
This is persistent, readable/writable, the os doesn't clear it and private.
"Persistent and private data storage within the application's sandbox using internal memory"
Within your program you can refer it this way: cordova.file.dataDirectory
For example here is a code from my app that download an image from a URL and put it to HTML in an image tag:
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem) {
var imageURL = "http://example.com/image.jpeg";
var ext = imageURL.substr(imageURL.lastIndexOf('.') + 1); //extension of the image
var relativeFilePath = "images/myimage" + "." + ext;
var ft = new FileTransfer();
ft.download(imageURL, fileSystem.root.toURL() + relativeFilePath, function(entry) {
var myImage= "<img src=" + fileSystem.root.toURL() + relativeFilePath + "' id=" + "imageID" + ">";
alert(fileSystem.root.toURL() + relativeFilePath); //kép
$('#imgdiv').html(myImage);
}, function(err) { alert("Download failure: " + JSON.stringify(err)); });
}, function(err) { alert("requestFileSystem failure: " + JSON.stringify(err)); });
In this code the fileSystem.root.toURL() refers to file:///data/data/com.phonegap.myapp/files/files/
and relativeFilePath is created by me, refers to images/myimage.jpeg
(for the download you need the file-transfer plugin, you can install with the
cordova plugin add org.apache.cordova.file-transfer command).
I hope this helps.
#Khalid You must create project manually:
project_folder
|___index.html
|___audio_folder
|___any resources or folder
Please check document from Phonegap Build
Edit 1: To play media file by Media object
// Get path 'www' in Android
function getPathApp(){
return location.href.slice(0,-10);
}
var media = new Media(getPathApp() + 'audio/file.wav');
// In IOS only need path from audio folder
var media = new Media('audio/file.wav');
media.play();

PhoneGap open file in native app. Build via build.phonegap.com

At first:
YES, there are many solutions in StackOverflow, but non of them works in my case.
I got application built in SmartGWT.mobile
I attached config files and all needed files to this build to prepare it for PhoneGap
Application is build via build.phonegap.com site.
It works perfectly fine on Android 4.1.1
I want to:
Download file to local filesystem it is an PDF file - It is working fine using:
var fileTransfer = new FileTransfer();
fileTransfer.download(.....
Open PDF in native app (for eg. Adobe Reader) whichever is installed on android for PDFs - it is not working:
I tried:
(1)
cordova.exec("ChildBrowserCommand.showWebPage", encodeURI(theFile.toURL()) );
(2)
window.plugins.childBrowser.showWebPage(encodeURI(theFile.toURL()));
(3)
window.open(encodeURI(theFile.toURL()), '_blank', 'location=yes');
(4)
even HTML5 plugin for open PDFs by firefox
All variations with "file://" without with "./" at front and so on.
childBrowser shows only white screen, each time adds "http://" at front, window.open - the same.
I finally found something interesting like WebIntent, so i did:
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
type: "application/pdf",
url: encodeURI(theFile.toURL().substring(7))},
function() {},
function() {alert('Failed to open URL via Android Intent')}
);
but its not working due to fact that phonegap-build not attaching class file and It can not find WebIntent Class
I declare this plugin using in config.xml:
<gap:plugin name="com.borismus.webintent.WebIntent" />
Do you know why it is not working, or what I'm doing worng ?
Maybe you know other way to open file just like that in native app, it suppose to be simple
I just want my app to download and show (in native app) the PDF for user.
don's FileOpener version have worked on my app cordova 3.0
phonegap local plugin add https://github.com/don/FileOpener
all the xmls, plugin, etc are then added automatically.
added fileopener.js on index.html
and then
window.plugins.fileOpener.open( path );
$("#page").on('pageshow', function(event, ui) {
if(event.handled !== true)
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
event.handled = true;
}
return false;
});
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
console.log("got filesystem");
// save the file system for later access
console.log(fileSystem.root.fullPath);
window.rootFS = fileSystem.root;
downloadImage(url, fileName);
}
function downloadImage(url, fileName){
var ft = new FileTransfer();
ft.download(
url,
window.rootFS.fullPath + "/" + fileName,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error" + error.code);
}
);
}

Phonegap Android app trigger update programmatically

I am building an Android app that is hosted on a server outside Google Play. I need the app to check for new version and prompt user to update when the app starts.
I built a mechanism to check for new version (the app checks for a file on server and compares version) which is working well. Then I prompt user to update, but if user chooses to proceed with the update, I'm not able to trigger the download and installation of the apk.
I tried simply opening the apk url:
window.open(apkURL);
where the apkURL is the full http link to the .apk file hosted on server.
But it doesn't seem to do anything.
I've been researching but I don't find an answer on how to do this. I found some suggestions using native code, like this post Install Application programmatically on Android but I don't know how to do that from within my Phonegap app.
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("file:///path/to/your.apk"))
.setType("application/vnd.android.package-archive");
startActivity(promptInstall);
Is this the right way to trigger the update? How can something like this be done from within a Phonegap app?
Thanks!
I finally managed to implement this, using the File api and the WebIntent plugin. I will post the solution here in case it helps anyone.
The code downloads the apk from a remote server to the download folder in the sdcard and then triggers the install.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile('download/filename.apk', {
create: true,
exclusive: false
}, function(fileEntry) {
var localPath = fileEntry.fullPath,
fileTransfer = new FileTransfer();
fileTransfer.download(apkURL, localPath, function(entry) {
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
url: 'file://' + entry.fullPath,
type: 'application/vnd.android.package-archive'
},
function(){},
function(e){
alert('Error launching app update');
}
);
}, function (error) {
alert("Error downloading APK: " + error.code);
});
}, function(evt){
alert("Error downloading apk: " + evt.target.error.code);
});
}, function(evt){
alert("Error preparing to download apk: " + evt.target.error.code);
});
For you guys that use Cordova 3+, a similar solution like that of Vero is possible:
So we're first going to download the .apk file. We need the file-transfer plugin for this.
You can install it with following command:
phonegap local plugin add org.apache.cordova.file-transfer
Secondly, we need another plugin to start a webintent. This webintent prompts the user if there is an update. You can install it with the following command:
phonegap local plugin add https://github.com/Initsogar/cordova-webintent.git
Then, you can use this 2 functions in your code to download the .apk and to prompt the user if
there is an update of the application:
/*
* Uses the filetransfer plugin
*/
function downloadApkAndroid(data) {
var fileURL = "cdvfile://localhost/persistent/CegekaMon.apk";
var fileTransfer = new FileTransfer();
var uri = encodeURI(data.android);
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,
{
}
);
}
/*
* Uses the borismus webintent plugin
*/
function promptForUpdateAndroid(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);
}
);
}
Sadly you cannot access that kind of native feature within a Phonegap web container without using a plugin, all you can do is link the user to the apk (by opening the native browser for instance) and let him install it.
thank you Vero for answer ... it is help me so much...
there is a problem with your code in cordova file plugin last version.
replace entry.fullPath with entry.toURL() if you use file plugin version 1.0.0 or newer.
if you use entry.fullPath , it throw error 'there is a problem parsing package'.
from file-transfer plugin on github
These paths were previously exposed in the fullPath property of FileEntry and DirectoryEntry objects returned by the File plugin. New versions of the File plugin, however, no longer expose these paths to JavaScript.
If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using entry.fullPath as arguments to download() or upload(), then you will need to change your code to use filesystem URLs instead.
FileEntry.toURL() and DirectoryEntry.toURL() return a filesystem URL of the form
cdvfile://localhost/persistent/path/to/file
which can be used in place of the absolute file path in both download() and upload() methods.
Working example in 2018
Based on previous comments I implement this solution
It require:
File plugin
File transfer plugin
Web intent plugin
constructor(public navCtrl: NavController, private transfer: FileTransfer, private file: File, private webIntent: WebIntent) {
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'urlApkFile';//Modified this
fileTransfer.download(url, this.file.externalDataDirectory + 'file.apk').then((entry) =>
{
webIntent.startActivity({
action: (window).plugins.intentShim.ACTION_INSTALL_PACKAGE,
url: entry.toURL(),
type: 'application/vnd.android.package-archive'
}).then(function () {
//OK
}, function (e) {
alert('Error launching app update' + JSON.stringify(e));
});
}, (error) => {
alert("downdload finish" + JSON.stringify(error));
});
}

Categories

Resources