How to download music that stored in http server in Angularjs - android

Let's say I have a API that stores some .mp3 music.
The sample link here:
https://118.69.201.34:8882/api/ApiMusic/Download?songId=2000
Now I want to write an API calling function in Angularjs to download the music to my Android devices with the song's Id number as in the link.
How can I do that? Please help :(

You can use the ngCordova FileTransfer library here: http://ngcordova.com/docs/plugins/fileTransfer/
Here's example code from that page, tweaked to your example URL:
document.addEventListener('deviceready', function () {
var fileid = "2000";
var url = "https://118.69.201.34:8882/api/ApiMusic/Download?songId=" + fileid;
var targetPath = cordova.file.documentsDirectory + fileid + ".mp3";
var trustHosts = true
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
}, function(err) {
// Error
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}, false);

I did it finally, here is my code. Just share for those who want to refer to this issue in the future. Thanks you guys for your answers
$scope.download = function(songId, songName) {
$ionicLoading.show({
template: 'Downloading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getDirectory(
"fMusic",
{
create: true
},
function (dirEntry) {
dirEntry.getFile(
songName + ".mp3",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI(APIUrl + songId),
p,
function (entry) {
$ionicLoading.hide();
$scope.mp3File = entry.toURL();
},
function (error) {
$ionicLoading.hide();
alert("Download Error Source --> " + error.source);
},
false,
null
);
},
function () {
$ionicLoading.hide();
console.log("Get the file failed");
}
);
}
);
},
function () {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}

Related

Cordova read external archive and play

I am creating an app with cordova for android using plugin file-transfer. The download is going to a certain folder but I can't read the file despite indicating the correct path follows the code
var uri = encodeURI(mypage);
var fileURL = cordova.file.externalDataDirectory + "teste.ogg";
fileTransfer.download(
uri, fileURL, function(entry) {
console.log("download complete: " + entry.toURL());
$("#audio-teste").attr('src',fileURL)
/*--codigo de teste--*/
var meuFile = cordova.file.externalDataDirectory;
resolveLocalFileSystemURL(meuFile, function(entry) {
var readerN = fileSystem.createReader();
readerN.readEntries(
function (entry) {
var arrayN =[];
for(var i="0"; i < entry.length; ++i){
var entradaN = entry[i].name;
arrayN.push(entradaN);
//console.log(array);
console.log('teste aq' + arrayN);
}
}
)
//console.log(entry);
});
/*----*/
},
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: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
/*----*/
The cordova plugin cordova-plugin-file-transfer is due to be deprecated and its latest npm version fails on iOS.
Therefore these two working functions are purely based on vanilla JS, and thus no need to use extra plugins, besides the standard plugin cordova-plugin-file. Therefore this is compatible with any platform.
https://gist.github.com/jfoclpf/07e52f6bdf9c967449c4bc06af44c94a
I paste here for your convenience:
// for different types of cordovaFileSystem check here:
// https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#where-to-store-files
// or simply type in the console `console.log(cordova.file)`
function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
var onerror = (err) => {
console.error(`Error downloading from ${fileurl} to cordovaFileSystem ${cordovaFileSystem}`,
err, new Error(err))
if (typeof callback === 'function') { callback(Error(err)) }
}
var blob = null
var xhr = new XMLHttpRequest()
xhr.open('GET', fileurl)
xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
xhr.onload = () => {
blob = xhr.response // xhr.response is now a blob object
var DataBlob = blob
window.resolveLocalFileSystemURL(cordovaFileSystem, (dirEntry) => {
const sanitizedFilename = filename.replace(/[^a-z0-9\.]/gi, '_').toLowerCase() // sanitize filename
dirEntry.getFile(sanitizedFilename, { create: true }, (file) => {
file.createWriter((fileWriter) => {
fileWriter.write(DataBlob)
if (typeof callback === 'function') { callback(null, cordovaFileSystem + sanitizedFilename) }
}, (err) => { console.error('Error on file.createWriter'); onerror(err) })
}, (err) => { console.error('Error on dirEntry.getFile'); onerror(err) })
}, (err) => { console.error('Error on resolveLocalFileSystemURL'); onerror(err) })
}
xhr.onerror = (err) => { console.error('Error on XMLHttpRequest'); onerror(err) }
xhr.send()
}
An example for downloading a file
downloadFileToDevice('https://example.com/img.jpg',
'myImg.jpg',
cordova.file.cacheDirectory,
(err, localFilePath) => {
if (err) {
console.error('An error occured downloading file:', err)
} else {
console.log('Download file with success: ' + localFilePath)
}
})
Can you try with this? I tried and it works like a charm

Phonegap WebIntent cannot open / access a downloaded APK file

From my Phonegap App I am downloading my APK which happens with no issues but I cannot get the file installed once its there.
The following bit of code just fails during the WEB INTENT section which should install the APk but its having trouble reading the file.
var apkFilePath = cordova.file.externalApplicationStorageDirectory+'myapp.apk';
// Android UPDATE routine
function downloadApkAndroid(data) {
var permissions = cordova.plugins.permissions;
permissions.hasPermission(permissions.WRITE_EXTERNAL_STORAGE, function (status) {
if (!status.hasPermission) {
var errorCallback = function () {
alert("Error: app requires storage permission");
if (callBack && callBack !== null) {
callBack();
}
};
permissions.requestPermission(permissions.WRITE_EXTERNAL_STORAGE,
function (status) {
if (!status.hasPermission)
errorCallback();
else {
downloadFile();
}
},
errorCallback);
}
else {
downloadFile();
}
}, null);
}
function downloadFile(){
var fileTransfer = new FileTransfer();
var url = "https://myappurl.com/myapp.apk";
var uri = encodeURI(url);
var filePath = getFilePath();
fileTransfer.download(
uri,
apkFilePath,
function (entry) {
console.log("Download complete: " + entry.fullPath);
promptForUpdateAndroid(entry);
},
function (error) {
console.error("Download error source " + error.source);
console.error("Download error target " + error.target);
console.error("Download error code " + error.code);
},
false,
{
}
);
}
/*
* Uses the borismus webintent plugin
*/
function promptForUpdateAndroid(entry) {
console.log(apkFilePath);
window.plugins.webintent.startActivity(
{
action: window.plugins.webintent.ACTION_VIEW,
url: apkFilePath,
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);
}
);
}
So figured this out by using cordova-plugin-file-opener2 and changing the promptForUpdateAndroid() to get rid of Web Intents:
var myFilePath = cordova.file.dataDirectory+'myApp.apk';
function promptForUpdateAndroid(entry) {
cordova.plugins.fileOpener2.open(
myFilePath,
'application/vnd.android.package-archive',
{
error : function(e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success : function () {
console.log('file opened successfully');
}
}
);
This instantly installed the app, though it didn't re-open once installed. I'm off to figure that out.

Error 5 getting directory when i take photo in Cordova app

I am getting photos, and i want to show them (it works) and save them on my directory. I followed mixed responses from this forum and w3c to obtain this code. My problem is when im getting the fileSys directory, it goes to onError, it cant get myFolderApp directory. Monitor shows "
Failed to ensure directory:
/storage/sdcard1/Android/data/tta.kirolapp.v1/files
and
Failed to ensure directory:
/storage/sdcard1/Android/data/tta.kirolapp.v1/files
This is normal because the app default directory is
/storage/emulated/0/0Android/data/tta.kirolapp.v1/
so, i think this is the problem but i don't know how to fix it.
The code of the functions which takes the photo and manage it, is the next:
function capturePhoto() {
alert('on capturePhoto');
sessionStorage.removeItem('imagepath');
//Cogemos la imagen y la codificamos en Base64
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, cameraDirection: 1, saveToPhotoAlbum:true, destinationType: Camera.DestinationType.FILE_URI });
}
function onPhotoDataSuccess(imageURI) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var imgProfile = document.getElementById('fotoRegistro');
// Pasamos la imagen a pantalla desde imageURI
//
console.log('El url por defecto es: '+ imageURI);
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1){
getLocation();
}
movePic(imageURI);
}
// Funcion onError
//
function onFail(message) {
alert('Failed because: ' + message);
}
function movePic(file){
window.resolveLocalFileSystemURL(file, resolveOnSuccess, resOnError);
}
//Callback function when the file system uri has been resolved
function resolveOnSuccess(entry){
console.log("Estoy en resolveOnSuccess");
var d = new Date();
var n = d.getTime();
//new file name
var identificacion= $('#idEmailReg').val();
var newFileName="foto"+identificacion+".jpg";
console.log ('El newFileName es: '+ newFileName);
var myFolderApp = "file:///storage/emulated/0/Android/data/tta.kirolapp.v1/img/";
//appConstants.localPermanentStorageFolderImg;
console.log ('El nuevo directorio es: '+ myFolderApp);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
console.log ('Entramos en el request onSuccess');
//The folder is created if doesn't exist
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory) {
console.log('El directory es: '+ directory);
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
//Callback function when the file has been moved successfully - inserting the complete path
function successMove(entry) {
//Store imagepath in session for future use
// like to store it in database
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error) {
alert(error.code);
}
resOnError shows code "5", and the monitor output is the next:
I use the media plugin and take the photos with photo capturing, this is the code:
function capturePhoto(){
//var fileFolder="/storage/emulated/0/KirolApp/img/";
var fileFolder=appConstants.localPermanentStorageFolderImg();
var identificacion= $('#idEmailReg').val();
var fileName="foto"+identificacion+".jpg";
photo.takeAsync(
fileFolder,
fileName,
function() {
console.log('En capturePhoto funcion');
var urlCompleta=photo.fileFolder+photo.fileName;
console.log('URL Completa: '+ urlCompleta);
$("#fotoRegistro").attr("src","file://"+urlCompleta+"?"+(new Date()).getTime());
}
);
}
On my objects.js file:
var photo = {
fileFolder:null,
fileName:null,
takeAsync: function(fileFolder,fileName,onSuccess) {
navigator.device.capture.captureImage(
function(photoFiles) {
var tempFullPath=photoFiles[0].fullPath;
tempFullPath=tempFullPath.substring(tempFullPath.indexOf("/"));
alert("New photo in: "+tempFullPath);
fileUtilities.moveAsync(tempFullPath,fileFolder,fileName,
function() {
photo.fileFolder=fileFolder;
photo.fileName=fileName;
if(onSuccess!=false)
onSuccess();
}
);
},
function(error) {
var msgText = "Photo error: " + error.message + "(" + error.code + ")";
alert(msgText);
}
);
}
};
And fileUtilities:
var fileUtilities = {
moveAsync: function (sourceFullPath,destFolder,destName,onSuccess){
var url="file://"+sourceFullPath;
var destFile=destFolder+destName;
var ft=new FileTransfer();
ft.download(url,destFile,
function() {
window.resolveLocalFileSystemURL(url,
function(fileEntry) {
fileEntry.remove(onSuccess);
},
function(error) {
alert("Source file NOT accesible; not removed");
}
);
},
function(error) {
alert('File not copied. '+'error.code: '+error.code+'\nerror.source: '+error.source+'\nerror.target: '+error.target+'\nerror.http_status: '+error.http_status);
}
);
}
};
Thanks to M.H and G.P from UPV/EHU.

Angular: cannot read property 'then' of undefined

I have a service upload imageto amazon s3 after i sign it with my own backend using cordova file-transfer plugin.
I call this service after taking a picture using cordova camera plugin to upload the taken picture to the s3 bucket.
The app sign correctly with my own backend but when it trigger the function upload i get the error i defined in the title.
This is the service that it call an end point in my backend to sign the file and then upload the image to amazon s3:
//Image upload Service
.factory('S3Uploader', function($q, $window, $http, $ionicPopup, API_URL) {
var signingURI = API_URL + "s3signing";
function upload(imageURI, fileName) {
document.addEventListener('deviceready', function() {
console.log('Uploading ' + fileName + ' to S3');
var deferred = $q.defer(),
ft = new FileTransfer(),
options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
console.log('Requesting signed doc ' + signingURI);
$http.post(signingURI, {
"fileName": fileName
})
.success(function(data) {
console.log('Got signed doc: ' + JSON.stringify(data));
options.params = {
"auth": true,
"key": fileName,
"AWSAccessKeyId": data.awsKey,
"acl": "public-read",
"policy": data.policy,
"signature": data.signature,
"Content-Type": "image/jpeg"
};
ft.upload(imageURI, "https://" + data.bucket + ".s3.amazonaws.com/",
function(e) {
console.log("Upload succeeded");
console.log(JSON.stringify(e));
deferred.resolve(e);
$ionicPopup.alert({
title: 'great',
content: 'The image upload to amazon success'
});
},
function(e) {
deferred.reject(e);
$ionicPopup.alert({
title: 'Oops',
content: 'The image upload failed to amazon'
});
}, options);
})
.error(function(data, status, headers, config) {
console.log(JSON.stringify(data));
console.log(status);
$ionicPopup.alert({
title: 'Oops',
content: 'The image upload failed to sign with node'
});
});
return deferred.promise;
}, false); //device ready
}
return {
upload: upload
}
})
and here is the controller code where am calling the camera plugin and in the success of taking the picture am calling the upload function from the S3Uploader service:
.controller('newItemCtrl', function($scope, $http, $ionicPopup, $timeout, $cordovaCamera, API_URL, me, S3Uploader) {
$scope.selectPicture = function() {
document.addEventListener('deviceready', function() {
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
$scope.imageSrc = imageURI;
// upload to Amazon s3 bucket
var fileName = new Date().getTime() + ".jpg";
S3Uploader.upload(imageURI, fileName).then(function() {
alert("upload to S3 successed");
});
}, function(err) {
alert(err);
});
}, false); // device ready
}; // Select picture
})
i get the erorr in this line of the controller:
S3Uploader.upload(imageURI, fileName).then(function() {
it's also important to mention am using crosswalk with my ionic app.
Your current implementation of S3Uploader.upload does not return a promise, it returns nothing. Move your declaration and return of the promise to directly inside the S3Uploader.upload function and not nested inside the document.addEventListener code.
Change your code to something like:
.factory('S3Uploader', function($q, $window, $http, $ionicPopup, API_URL) {
var signingURI = API_URL + "s3signing";
function upload(imageURI, fileName) {
var deferred = $q.defer()
document.addEventListener('deviceready', function() {
// Removed for brevity
}, false);
return deferred.promise;
}
return {
upload: upload
}
})
You are creating and returning your deferred object and it's promise from an event listener. Not the upload factory method.
Something along these lines is what you need:
.factory('S3Uploader', function($q) {
function upload() {
var deferred = $q.defer();
// listener logic
return deferred.promise;
}
return {
upload : upload
}
});
You will have problems with this, as you will want a new deferred object for each time the listener is fired. Adding a listener to a factory method to perform something seems like a bad pattern to me. The event should wrap the invocation of the factory method.

How to store and retrieve files in/from android app space?

I'm developing a cordova/phonegap app. Right now, I'm testing the app on Android.
If I include files (audio, video, ...) by default, I can access to that files indicating the "url" like audio/filesong.mp3 or video/filevideo.mp4.
But if I download files with the next code:
function downloadFile() {
var fileTransfer = new FileTransfer();
var uri = encodeURI("UrlOfTheFile");
var fileURL = "cdvfile://localhost/persistent/appcustomstorage/";
fileTransfer.download(
uri, fileURL + "file.extension", 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=="
}
});
}
I download the file in StorageRoot/appcustomstorage/file.extension
It is possible to store the file in the app package, i.e., in, for example, Android/data/com.example.app??
Or a method to get the Android/data/com.example.app url and then add the necessary folder?
Solution:
In this case I find all mp3 in the device. It works on Nexus 4.
index.html
<ul data-role="listview" data-inset="true" id="ulsongs">
</ul>
index JavaScript:
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
FileSystem = fileSystem;
// Call to start to find all files
getFileSystem();
}
storageScript:
var FileSystem = null;
var AudioExtensions = [ '.mp3' ];// , '.wav', '.m4a' ];
var my_media = null;
function listDir(directoryEntry, level) {
if (level === undefined)
level = 0;
var directoryReader = directoryEntry.createReader();
directoryReader.readEntries(function(entries) { // success get files and
// folders
for ( var i = 0; i < entries.length; ++i) {
if (entries[i].name === '.')
continue;
if (entries[i].isDirectory) {
FileSystem.root.getDirectory(entries[i].fullPath.slice(1,
entries[i].fullPath.length), {
create : false
}, function(dirEntry) {
listDir(dirEntry, level + 1);
}, function(error) {
console.log('ERROR');
alert(error.code);
});
}
if (entries[i].isFile) {
var extension;
extension = entries[i].name.substr(entries[i].name
.lastIndexOf('.'));
if (entries[i].isFile === true
&& $.inArray(extension, AudioExtensions) >= 0) {
// Add a song to the list
$("#ulsongs").append(
"<li id='" + entries[i].fullPath + "'"
+ " data-icon=\"audio\"><a>"
+ entries[i].name + "</a></li>");
$('#ulsongs').listview('refresh');
}
}
}
}, function(error) { // error get files and folders
alert('Error. Code: ' + error.code);
});
// Action listener
$('#ulsongs li').click(function(e) {
pathsong = $(this).attr('id');
console.log('item clicked. Path: ' + pathsong);
if (typeof (pathsong) != 'undefined' && pathsong != null) {
// Stop previous song
if ((audio_status != null) && (audio_status == 2)) {
console.log('STOP AUDIO');
my_media.stop();
my_media.release();
}
// Play the audio file at url
my_media = new Media(pathsong,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: " + err);
}, status);
// Play audio
my_media.play();
}
});
}
var audio_status = null;
function status(stat) {
audio_status = stat;
}
/**
*
*/
function getFileSystem() {
console.log('entra getFileSystem');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) { // success get file system
var sdcard = fileSystem.root;
sdcard.getDirectory('', {
create : false
}, function(dirEntry) {
listDir(dirEntry);
}, function(error) {
alert(error.code);
})
}, function(evt) { // error get file system
console
.log('ERROR GETTING FILE SYSTEM'
+ evt.target.error.code);
});
}
I create a list of mp3.
I use jQuery and jQueryMobile
Edit
The process may need a bit of time. It is recommended to show a loading popup.

Categories

Resources