Phonegap how to download and open pdf file in android app - android

recently i am working on a android apps build in phonegap, i am quite new with mobile development and this i smy first appsbut, and i am stuck when try to download some documents (pdf, doc, jpg) to local storage and open it, after search through google and i tried to follow this solution.
I followed the exact code in the example and below is how i call the plugins:
window.plugins.downloader.downloadFile(url,'/sdcard/download/', 'test.pdf', true, downloadOkCallbak, downloadErCallbak);
window.plugins.pdfViewer.showPdf('/sdcard/download/test.pdf');
The url is my remote file, when i execute it, i got error: "TypeError: window.plugins is undefined". Anyone help is appreciated.
[update] My code of showPdf function:
public String showPdf(String fileName) {
File file = new File(fileName);
if (file.exists()) {
try {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setData(Uri.parse(fileName));
this.ctx.startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
System.out.println("PdfViewer: Error loading url "+fileName+":"+ e.toString());
return e.toString();
}
}else{
return "file not found";
}
}
[Update 2] I got below error in web console: Uncaught ReferrenceError: LocalFileSystem is not defined at ...
What could be the issue?

I had the same problem as the OP and many unsuccessful approaches later I came to the following solution (tested with Cordova 3.1.0-3.3.0 & Samsung Galaxy S3 & iOS 7):
Solution
First, get the file by requesting the file system and then download it from your server with fileTransfer.download(). After completing the download call the FileOpener (which will open a pop up where to choose from apps like Adobe Reader). Note: Make sure to include the FileTransfer feature via CLI/Terminal: cordova plugin add org.apache.cordova.file
Navigate to your project folder
Open CLI/Terminal and type in: cordova plugin add https://github.com/don/FileOpener.git
After successful download and storage of your file on the device (see above) you open it with: window.plugins.fileOpener.open("file:///sdcard/Android/data/com.example.application/document.doc") or the appropriate path on iOS.
That's it! Good luck!

Make sure you've had these lines in your manifest.xml :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can find help here How to download a pdf file in Android?

Make sure
You should install git and install file plugins(cordova 3.0+)
File and file transfer plugin
$ cordova plugin add org.apache.cordova.file
$ cordova plugin add org.apache.cordova.file-transfer
Ps. Try plugin fileOpener2
https://build.phonegap.com/plugins/1117

Try this to open any kind of documents from URL using following steps:
install this plugin : cordova plugin add https://github.com/ti8m/DocumentHandler
use this code :
handleDocumentWithURL(function() { console.log('success'); }, function(error) { console.log('failure'); if (error == 53) { console.log('No app that handles this file type.'); } }, 'http://www.example.com/path/to/document.pdf');
It works for me both on Android and IOS. I used it for open images and PDF files.
Android : It opens files using system apps if available, otherwise it give an error, which you can handle.
IOS : It opens files in popup like view with Done button and Option button.
It doesn't show your docs URL.
Source is available here : https://github.com/ti8m/DocumentHandler

Related

Cordova File Plugin: SECURITY_ERR

I have a hybrid app in production (iOS/Android) that uses Cordova plugins. I have one Android user who is getting a SECURITY_ERR when using the File plugin. This seems to be happening on a call to writeFile(). The file path I'm writing to for Android is externalRootDirectory.
Can anyone help me understand why 1 user (out of 300-400) would have this problem? The user is on Android 6.0.1 if that helps.
Some code is below. The error I'm getting is [Error creating file] – Error Msg: [SECURITY_ERR], so the .writeFile() catch is being hit in this case.
//Handle Native download
if (this.appConfig.isNative) {
this.loggingService.debug("Starting to create native file");
//Get base file path for android/ios
let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;
//Write the file
this.file.writeFile(filePath, fileName, data, { replace: true })
.then((fileEntry: FileEntry) => {
this.loggingService.debug("Created file: " + fileEntry.toURL());
//Open with File Opener plugin
this.fileOpener.open(fileEntry.toURL(), data.type)
.then(() => this.loggingService.debug('File is opened'))
.catch(e => this.loggingService.error('Error openening file', e));
})
.catch((err) => {
this.loggingService.error("Error creating file", err);
throw err; //Rethrow - will be caught by caller
});
}
I was able to figure this one out. Looks like after Android 6.0 certain permissions must be requested during use of the app (not just at install time). This is also alluded to in the Cordova File plugin docs, under Android Quirks.
Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By default, your app has permission to write to cordova.file.applicationStorageDirectory and cordova.file.externalApplicationStorageDirectory, and the plugin doesn't request permission for these two directories unless external storage is not mounted. However due to a limitation, when external storage is not mounted, it would ask for permission to write to cordova.file.externalApplicationStorageDirectory.
So on Android 6.0+, when writing a file to disk the Cordova File plugin will display a prompt similar to:
Allow APP_NAME to access photos, media and files on your device?
If the user selects Deny to this request, then the Cordova file write will get this SECURITY_ERR, even if the app requests this permission at install time.

window.resolveLocalFilesystemUrl in ionic 2

I need to save a downloaded file in my ionic 2 path and use that ineteral url path.
for downloading: using file-transfer plugin.
const fileTransfer = new Transfer();
fileTransfer.download(trackObj.remoteUrl,cordova.file.dataDirectory+"audio/"+filename).then((entry)=>{
console.log("download completed:"+entry.toURL());
});
entry.toURL() is giving path like file://...... in need to use that path to play using Media plugin. But, Media plugin is not accepting path with file://...,
this.playerStatic = new MediaPlugin(internalFilePath,onStatusPlayerUpdate);
so, on googling foundout: https://forum.ionicframework.com/t/ios-9-cant-play-audio-video-files-that-are-downloaded-to-device/37580/4
so using "cdvfile://localhost/library-nosync/" + fileSrc; as a temporary solution. Its not working for android.
so to be able to use in both platforms, i should be able to follow other solution, where the path will be resolved to InternalURL. when i try
window.resolveLocalFileSystemURL(src, function(dir){});
its saying resolveLocalFileSystemURL is not a function.
anybody can help me with it? how to use window.resolveLocalFileSystemURL in ionic 2?
I am using it in ionic 3, for iOS build. Please check the code:
this.file.resolveLocalFilesystemUrl(this.file.dataDirectory).then((entry) => {
console.log("Success! Got a DirectoryEntry",entry);
});
Here, I am using cordova-plugin-file but I think it should work for cordova-plugin-file-transfer also. Please try and let me know, if there is any issue.

cannot use cordova plugin to open files under ionic 2 and typescript

I am developing an android app based on ionic 2 using typescript.
I would like o open a PDF file inside my app with another app that is registered for the fyletype (e.g. Acrobat Reader).
Therefore i tried the two standard plugins:
https://github.com/disusered/cordova-open
https://github.com/pwlin/cordova-plugin-file-opener2
Although ive added both plugins via "ionic plugin add ..." and of course played around with several combination referencing to it
the result is always that they ere not found
cordova-open
var open = cordova.plugins.disusered.open;
Property 'disusered' does not exist on type 'CordovaPlugins'.
cordova-plugin-file-opener2
cordova.plugins.fileOpener2.open(
filePath,
fileMIMEType,
{
error : function(){ },
success : function(){ }
}
);
Property 'fileOpener2' does not exist on type 'CordovaPlugins'.
I am running the app on an emulator via ionic run android
Could you please give some hint how i can achieve to use one of these plugins?
Thank you very much
Shane

Ionic Cordova FileUpload error: Not allowed to load local resource

I am new to Ionic and I am trying to upload an image taken from camera that is stored in Android filesystem:
var ft = new FileTransfer();
console.log('Uploading: ' + fileURL);
ft.upload(fileURL,
encodeURI("http://192.168.192.62:3000/api/meals/picture"),
pictureUploaded,
function(error) {
console.err(error);
$ionicLoading.show({template: 'Ooops error uploading picture...'});
setTimeout(function(){$ionicLoading.hide();}, 3000);
},
options);
var pictureUploaded = function() {
console.log('uploaded!');
$ionicLoading.hide();
};
fileUrl is pointing to an existent image: file:///data/data/com.ionicframework.nutrilifemobile664547/files/Q2AtO1462636767466.jpg
In chrome://inspect/#devices console I get the following error and it looks like because of the error the FileOptions are also not properly sent, this is the error (Not allowed to load local resource):
Cordova version: 6.1.1
Ionic version: 1.7.14
This happens when you use the "livereload" option with Ionic.
Try running in normal mode
With ionic webview >3.x, you have to use convertFileSrc() method.
For example if you have a myURL local variable such as file:// or /storage.
let win: any = window; // hack ionic/angular compilator
var myURL = win.Ionic.WebView.convertFileSrc(myURL);
Another possible reason is that you have a webview plugin installed (like https://github.com/ionic-team/cordova-plugin-ionic-webview or just https://github.com/apache/cordova-plugin-wkwebview-engine). Also this will not allow to use cdvfile:// protocol as well.
It might be too late but... you could convert native path to blob using File then convert blob to URL using URL.createObjectURL(blob) and passing/setting as src to your html element. This is unnecessary for production environment but you could use it for development with -lc. It might work
07-Dec-2018
This is the version where it works for me on Ionic 3.9.2 app.
Remove the latest version of webview and then:
i.e. ionic cordova plugin add cordova-plugin-ionic-webview#1.2.1
https://github.com/ionic-team/cordova-plugin-ionic-webview/releases/tag/v1.2.1
Note: This version works fine with normalizeURL() method.

Can a Cordova Android app write in its native source folder?

I would like to know if an Android app using Cordova can write in the folder that it is installed in. Basically, I need this to update the app without having to go through the app store.
In iOS, ressources files are copied in a sandboxed environment and I cannot write to it. What about in Android?
Yes ,cordova can write into the app folder or in anyfile which it Android can access , if you want to write in private other folder that wont be possible .
For cordova you need to just add a plugin for accessing the storage or create a custom plugin for the same.
Below is code for writing into your App Folder :
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("Log", "No sdcard available");
} else {
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"ApplicationFolderName");
directory.mkdirs();
}
Make sure you add permission into manifest file also.

Categories

Resources