cordova: download from url to android download folder - android

Well before i start i tried below answers from stack overflow.
Download file to downloads folder ios/android using phonegap
FileTransfer Cordova download path
Download a file to Downloads folder of device using Cordova FileTransfer
http://www.phonegaptutorial.com/downloading-an-image-from-the-internet-with-phonegap/
But no luck at all.
I am trying to download a file from internet.
My target is to download the file in download folder on Android phone.
I tried all the above answers and also i have used cordova example from cordova site.
https://cordova.apache.org/docs/en/2.0.0/cordova/file/filetransfer/filetransfer.html
function downloadCL(){
var url = "http://www.phonegaptutorial.com/wp-content/uploads/examples/phonegap-logo.png";
// we need to access LocalFileSystem
window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, function(fs)
{
// create the download directory is doesn't exist
fs.root.getDirectory('downloads', { create: true });
// we will save file in .. downloads/phonegap-logo.png
var filePath = fs.root.fullPath + '/downloads/' + url.split('/').pop();
var fileTransfer = new window.FileTransfer();
var uri = encodeURI(decodeURIComponent(url));
fileTransfer.download(uri, filePath, function(entry)
{
alert("Successfully downloaded file, full path is " + entry.fullPath);
},
function(error)
{
console.log("Some error " + error.code + " for " + url +);
},
false);
}
};
};
Any advise how to achieve this.

Fork,
you have to choose download file url,
local download file located here -
file:///storage/emulated/0/download
This link may help you -
Cordova - Download a file in download folder
Added file transfer plugin to download such as -
https://github.com/cfjedimaster/Cordova-Examples/tree/master/asyncdownload
choose any as per requirement

Related

Download a file to Downloads folder of device using Cordova FileTransfer

I am using Cordova FileTransfer object to download a file from a url to device.
var fileTransfer = new FileTransfer();
var path = cordova.file.dataDirectory;
fileTransfer.download(
fileUrl,
path + "/sample.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
alert("File downloaded to "+cordova.file.dataDirectory);
},
function(error) {
console.log(JSON.stringify(error));
}
);
In this case the file is downloaded to data/data/com.fileDemo/files/
(I am not sure whether download is success as I can't access this folder. Getting success message as download complete: file:///data/data/com.fileDemo/files/sample.pdf).
How can I use the same method to download a file to "Downloads" folder of the android device?
In Cordova, with FileTransfer, you can request TEMPORARY or PERSISTENT file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fail);
iOS
PERSISTENT will return the Documents directory,
TEMPORARY will return the Caches directory
Android
PERSISTENT will returns the root of the SD card/phone memory
TEMPORARY will return a folder inside the data folder.
Refer File API & FileTransfer for more info.

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 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