Local file phonegap with online building app - android

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();

Related

Cordova plugin background download fails

I need to download huge file ( 160GB ) using my Cordova application. As file-transfer plugin was deprecated and suggested XMLHTTPRequest usage fails for huge failes, I downloaded cordova-plugin-background-download from https://github.com/sgrebnov/cordova-plugin-background-download. It works great for any iOS device, but it always fails on Android 13 with error
Unsupported path /storage/emulated/0/ ......
The error is when a temporary file is being crated. I assume, the problem is with this code:
this.setTempFileUri(Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory().getPath(),
Uri.parse(targetFileUri).getLastPathSegment() + "." + System.currentTimeMillis())).toString());
where
android.os.Environment.getExternalStorageDirectory().getPath()
returns invalid path.
Is there a workaround, how to make the plugin working on Android 13? I use the sample code from the plugin homepage on Github.
Line 114 of the src/android/BackgroundDownload.java file needs to be modified for proper functionality from
this.setTempFileUri(Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory().getPath(),
Uri.parse(targetFileUri).getLastPathSegment() + "." + System.currentTimeMillis())).toString());
to
this.setTempFileUri(Uri.fromFile(new File(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS),
Uri.parse(targetFileUri).getLastPathSegment() + "." + System.currentTimeMillis())).toString());

Nativescript: How to save a file in external storage (SD card)

After a lot of googling, and a lot of tries with "out-of-context" code, I'm begging you to help me.
I'm trying to figure out if it's possible to write on the external storage with Nativescript. I'm not interested to write within the application context. So what the docs shows, it's not what i'm looking for.
I've managed to achieve this from a thread on the Nativescript forum:
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
It works, it gives me a path, but when I have this path I have no clue of what to do with it. How to create a file inside that path, read it etc.
What I need to achieve is to create a folder that both the user and the application can easily access. The user should be able to access this folder with the builtin files explorer.
The application runs on Angular.
I really struggled with this one on Android device and in the end it was due to:
Not making sure the required permissions has been granted by the user in the app
Using "Android File Transfer" on my Macbook to verify the files have been created and to download them
tns info
nativescript 6.0.3
tns-core-modules 6.0.7
tns-android 6.0.2
tns plugins
nativescript-permissions 1.3.7
example code
import * as fs from "tns-core-modules/file-system"
...
// First get the required permissions
// Note: this permissions should also be in your AndroidManifest.xml file as:
// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
const permissions = require('nativescript-permissions')
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
.then(() => {
console.log('Required Android permissions have been granted');
})
.catch(() => {
console.error('Required Android permissions have been denied!');
});
// Get the publicly accessable Downloads directory path
const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
console.log('sdDownloadPath: ' + sdDownloadPath)
// Get a specific folder in that path (will be created if it does not exist)
const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
console.log('myApp path: ' + myAppFolder.path)
// Get a file in that path (will be created if it does not exist)
// Note: In this case we try to get a unique file every time this code is run
let date = new Date()
date = date.toISOString().replace('.', '')
const myFile = myAppFolder.getFile(`myfile_${date}.txt`)
console.log('myFile path: ' + myFile.path)
// Write some data to this new file
myFile.writeText('Hello duder 123')
.then(() => {})
.catch((err) => console.log(`Error writing to file: ${err}`))
// Try and read back the data that was written
myFile.readText()
.then((res) => {
console.log(`Text read back: ${res}`)
}).catch((err) => {
console.log(err.stack);
});
// List all files in the myApp folder
myAppFolder.getEntities()
.then((entities) => {
// entities is array with the document's files and folders.
entities.forEach((entity) => {
console.log(entity)
});
}).catch((err) => {
console.log(err.stack);
});
android file transfer issue
One problem I wasted a lot of time on was that I could see the files with getEntities() but could not see them when using the 3rd party tool "Android File Transfer (AFT)" on Mac. I eventually stumbled across "Android Studio's -> Device File Explorer" and could see all my created files and folders with it so realised the issue is with AFT.
I now make use of Airdroid to browse and download device files.
applicable reference
https://docs.nativescript.org/angular/ng-framework-modules/file-system
(angular docs but relevant to nativescript-vue as well)
Do you know your external(sd card) path?
If it is like /storage/emulated/0, then you could try this to create a folder or file.
import * as fs from "tns-core-modules/file-system";
let externalPath= fs.path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString());
//Create a folder with known path
var folder: fs.Folder = fs.Folder.fromPath(sdCardPath+"/test");
//Create a file
var testFile: fs.File = folder.getFile("test.txt");
console.log("Path " + folder.path)
User should be able to access this fold and file. It is in device internal storage which is "external" folder.
I still try to figure out how to get access to sd card but hope above code work for you.
I have the same issue and finally solved it by adding android:requestLegacyExternalStorage="true" inside the AndroidManifest.xml file
follow the thread here

cordova: download from url to android download folder

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

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.

How to use FileTransfer.download on 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);
}
);

Categories

Resources