Where to save a PDF on Android device using FileTransfer plugin Phonegap - javascript

I am trying to download a PDF in my phonegap application and then immediately open it, but I get a File not Found error. It seems to download. Here is my code:
// Download
var url = "https://example/example.pdf";
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
var fileName = 'example.pdf';
fileTransfer.download(
uri,
fileURL,
function (entry) {
alert("download complete: " + entry.fullPath);
// Open
cordova.plugins.fileOpener2.open(
fileURL + fileName,
'application/pdf',
{
error: function (errorObj) {
alert('Error status: ' + errorObj.status + ' - Error message: ' + errorObj.message + ' ' + errorObj.fileURL);
},
success: function () {
alert('file opened successfully');
}
}
);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
alert('Downloading...');
I'm also wondering where is the best place to save files like this, that should be available after the app is closed?

second argument to fileTransfer.download is the location on device where you want to download pdf file.
You are setting var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/'; Which I believe does not exist. You can use file system plugin to first get file location on your device and then save it on device. you can use below code snapet.
var url = "https://example/example.pdf";
var uri = encodeURI(url);
//var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
// var fileName = 'example.pdf';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getDirectory("Dir_NAME", {
create: true,
exclusive: false
}, gotDirectory, fail);
}
function gotDirectory(entry) {
entry.getFile('yourFileNAme', {
create: true,
exclusive: false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
filePath = fileEntry.fullPath;
var fileTransfer = new FileTransfer();
fileTransfer.download(
'uri', filePath, function(entry) {
console.log("success");
//perform you launch task
}, function(error) {
console.log("error");
}, true, {});
}
I hope it will help you.

Even I am new to android but what I think that there is problem in URI
To open up a Uri in android it should have a structure like
file:///storage/....
(there should be 3 backslashes )
You can get more details here
The best place to save a pdf can be your sdcard or internal storage. Then the pdf will be available in your device even after the application closes.
If you wish to have the same pdf file, available in different devices while testing your application in different device/ or even in emulator you can save it in the assert folder of your android project.
hope this helps

Related

Cordova file transfer image is not uploading the file to server

Please help me to resolve this issue, am try to solve this from last week. Using cordova file transfer plugins am try to upload my image to production server
however am getting error code 1.
i checked source and target path both are accessible. Please find my cordova setup versions.
Cordova -> 7.1.0, Phonegap -> 7.1.1, cordova-plugin-file-transfer-> spec=1.7.1
Code:
function staticpathu_upload() {
var fileURL = 'https://example.com/Al_2_1518090802.jpg';
var uri = encodeURI('https://example.com/dummy.php');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(fileURL, uri, onSuccess, onError, options);
function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onError(error) {
console.log(error);
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Error:
FileTransferError {
code: 1,
source: "https://example.com/Al_2_1518090802.jpg",
target: "https://example.com/dummy.php",
http_status: null,
body: null,
}
This issue with ServerUrl, its not allowing me to post the image to server. I have created dummy.php on server root folder and execute from below code its working fine. It won't work from desktop we have check in mobiles or emulators only.
function uploadphoto(){
navigator.camera.getPicture(uponSuccess, uponFail, { quality: 50,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
destinationType: Camera.DestinationType.FILE_URI
});
// Change image source and upload photo to server
function uponSuccess(imageURI) {
// Set image source
var image = document.getElementById('fileuploadimg');
$$('.gAlbumList').append('<img src="'+imageURI + '?' + Math.random()+'" />');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "https://example.com/dummy.php", function(result){
$$('.error').append('<p>successfully uploaded ' + result.response+'</p>');
}, function(error){
$$('.error').append('<p>error : ' + JSON.stringify(error)+'</p>');
}, options);
}
function uponFail(message) {
$$('.error').append('<p>Failed because: ' + message+'</p>');
}
fileUrl must be a
Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device. (See Backwards Compatibility Notes below)
See the docs
This is propably the reason why a FileTransferError.FILE_NOT_FOUND_ERR (error code 1) is thrown.

mp3 Download Ionic Framework | Android | HTML5

I am working on ionic framework for android .
It simply contains an Iframe to embed a website in a blank project.
This is the website http://www.ultrayoutube.com/ANDROID/#/wanna.
I am facing two problems
Making Iframe equal to size of screen
I want Iframe to be equal to the size of window . I am using <iframe src="http://www.ultrayoutube.com/ANDROID/#/wanna" style="width:100%; height:100%;" ></iframe>
But iframe only takes 1/2 of screen in emulator
When the user searches for the song he must be able to download it by clicking download mp3
I have gone through some plugins as file transfer plugins but they all need a download link to download something . I want it that when the user clicks on button download mp3 , that link is automatically passed to the plugin and is downloaded to user's cell phone .
on Document Head try to initialise your file transfer plugin
function onDeviceReady() {
console.log('deviceready');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
window.fs = fileSystem;
window.fileTransfer = new FileTransfer();
window.fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
console.log(perc + '%');
$('.progress-bar').css({width: perc + '%'});
}
};
window.fs.root.getDirectory('Download', {create: true}, function(dirEntry) {
window.downloadFolder = dirEntry;
});
},
function(evt) {
console.log(evt.target.error.code);
}
);
}
Change : script.js
app.run(function($rootScope, downloader, alertService) {
$rootScope.fs = window.fs;
$rootScope.downloadFolder = window.downloadFolder;
$rootScope.fileTransfer = window.fileTransfer;
$rootScope.messages = {}
...
$rootScope.saveContent = function(url) {
var uri = encodeURI(url);
$rootScope.fileTransfer.download(
uri,
$rootScope.downloadFolder.toURL() + "/" + url.substring(url.lastIndexOf('/') + 1),
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
}
);
};
...

Contact image from Phonegap not displayed

I saw several posts related to this like Ref but not working for me . I tried like below
First method:
Directly set image source from contact image value
var myImg = document.getElementById("cimg");
myImg.src = contacts[i].photos[0].value;
this one not display the image in img tag.
Second Method:
Pass the contact image value to the fileDownload option
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fs){
fs.root.getFile("temp.jpg", {create: true, exclusive: false},
function(entry){
//alert(entry.toURL());
var fileTransfer = new FileTransfer();
fileTransfer.download(
contacts[i].photos[0].value, // the filesystem uri you mentioned
entry.fullPath,
function(entry) {
// do what you want with the entry here
console.log("download complete: " + entry.fullPath);
var src = entry.fullPath;
//$("").append('<img src="'+src+'" >');
},
function(error) {
alert("error source " + error.source);
console.log("error target " + error.target);
console.log("error code " + error.code);
console.log(error);
},
false,
null
);
}, function(e){
console.log("file create error",e);
});
}, null);
This one shows error like 07-28 07:37:56.468: E/FileTransfer(20986): {"target":"file:\/\/\/mnt\/sdcard\/Android\/data\/io.cordova.hellocordova\/cache\/temp.jpg","http_status":0,"code":3,"source":"content:\/\/com.android.contacts\/contacts\/2\/photo","exception":"read failed: EINVAL (Invalid argument)"}
07-28 07:37:56.468: E/FileTransfer(20986): java.io.IOException: read failed: EINVAL (Invalid argument)
Edit :
my phonegap contact[i].photo[0].value return like "content://com.android.contacts/contacts/1/photo"
how to resolve this one. Please help me.
please check what android version you are testing. Because there have a lot changes structures android 2.0 -> 2.2.. Can you try on android above 4.0 + ?

How to download a video file from a link in phonegap?

Let suppose i have an .mp4 vedio on server. i want to download it in android phone, how i can do it.. Please guide me with some code
<script>
function downloadImage(url,fileName){
var fileTransfer = new FileTransfer();
fileTransfer.download(
url,
window.rootFS.fullPath+ "/" + fileName,
function(entry) {
alert(\"download complete: \" + entry.fullPath);
},
function(error) {
alert(\"download error\"+JSON.stringify(error));
}
);
}

How to download a file from URL in android using phonegap?

I want to download a file from URL.Like if i click on download button the file url should get connect and it should get downloaded into phone memory or SDCard of android.
Can anyone please help me how to get this to work using phonegap?
Thank you.
Please use the FileTransfer API from Phonegap or CoreDova. Here is the sample code from the same source:
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");
fileTransfer.download(
uri,
filePath,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
To save the file on SDCard use FileWriter
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
}
function fail(error) {
console.log(error.code);
}

Categories