I have generated a PDF invoice using the file plugin. Now I want to open the file in the app. I tried inAppBrowser, but its giving an empty page. I tried fileopener, its neither giving a success or failed message. How do I specify the path to my file . please help!!
In app Browser Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
cdr=dir;
alert("cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log(" write success");
};
console.log("writing to file");
writer.write( pdfOutput );
},function () {
console.log("ERROR SAVEFILE");
});
});
});
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
alert("open file");
dir.getFile("test.pdf", {create:false}, function(fileEntry) { //EXISTS
alert("native url "+cdr.toNativeURL());
var url =cdr.toNativeURL() + "test.pdf";
alert(url);
window.open(url, '_blank');
}, function() { //NOT EXISTS
alert("no file found");
});
});
}
Fileopener Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory , function(dir) {
cdr=dir;
console.log(" vidhya cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log("vidhya write success");
openFile(cdr);
};
console.log("vidhya writing to file");
writer.write( pdfOutput );
},function () {
console.log("vidhya ERROR SAVEFILE");
});
});
});
function openFile(cdr) {
var fs;
function fsSuccess(fileSystem)
{
fs = fileSystem;
console.log("vidhya "+fs);
}
function fsFail(event)
{
console.log(event.target.error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsFail);
console.log("vidhya opening file " +cdr.toNativeURL());
cordova.plugins.fileOpener2.open(
fs.root.toURL() +'test.pdf',
"application/pdf", //mimetype
{
error: function(e) {
alert("Error Opening the File.Unsupported document format.");
},
success: function() {
// success callback handler
alert("success");
}
}
);
}
My file is getting saved in /internal storage/Android/Data/app_folder/files/test.pdf
This is how i made it work in my hybrid mobile app:
var cdr;
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
function onError(e) {
navigator.notification.alert("Error : Downloading Failed");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("Cordova", {
create: true,
exclusive: false
}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
dir.getDirectory("My_App", {
create: true,
exclusive: false
}, onGetDirectorySuccess1, onGetDirectoryFail);
};
function onGetDirectorySuccess1(dir) {
cdr = dir;
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
var documentUrl = "http://myserverurl.com/test.pdf";
var uri = documentUrl;
fileTransfer.download(uri, cdr.nativeURL + docFileNameToView,
function(entry) {
openFile();
},
function(error) {
navigator.notification.alert("Error");
},
false
);
};
function openFile() {
cordova.plugins.fileOpener2.open(
cdr.nativeURL + docFileNameToView,
'application/pdf', {
error: function(e) {
navigator.notification.alert("Error Opening the File.Unsupported document format.");
},
success: function() {
}
}
);
};
function fail(error) {
navigator.notification.alert("Error");
};
function errorHandler(e) {
navigator.notification.alert("Error");
};
function onGetDirectoryFail(error) {
navigator.notification.alert("Error");
};
This code uses cordova file transfer plugin to download pdf and file opener plugin to view the pdf. This sample code also use device plugin to get the device platform (iOS or Android) and dialog plugin to display notification.
Code was tested on iOS 9 and Android 6 devices and works fine. In Android, the file gets stored in storage/emulated/0/Cordova/My_App folder
If someone faces an issue while opening the file stored in device even with proper destination file path specified, please do ensure that the file is downloaded properly without corruption.
Many a times file opening fails due to improper or corrupted download. You can also trace any error during download using chrome inspect devices option. Also ensure to use latest version of file transfer plugin to avoid download error.
Related
I am creating a image download server for my APP with Rest API, there are two buttons in the HTML, one is download button and other is load button.
When clicked on download button progress bar shows the progress, but there is no output file and doesn't show any error even load button doesn't load anything.
This script works fine with static URL (without API) by making certain changes in the script.
Link for my temporary Server.
http://freaksearch.com/aarti/rest-api.php?json=image&Id=
Plugin required by this script : cordova-plugin-file-transfer
(this is not depreciated plugin)
Link for the plugin: https://www.npmjs.com/package/cordova-plugin-file-transfer
Here is my HTML:
<div class="padding">
<button class="button" ng-click="download()">Download</button>
<button class="button" ng-click="load()">Load</button>
{{imgFile}}
<img ng-src="{{imgFile}}">
</div>
Here is my script:
$scope.download = function(imageId, imageName) {
$ionicLoading.show({
template: 'Downloading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getDirectory(
"MyProject",
{
create: true
},
function (dirEntry) {
dirEntry.getFile(
imageName + ".jpg",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI('http://freaksearch.com/aarti/rest-api?json=image' + imageId),
p,
function (entry) {
$ionicLoading.hide();
$scope.imgFile = 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");
});
}
$scope.load = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
"MyProject",
{
create: false
},
function(dirEntry) {
dirEntry.getFile(
imageName + ".jpg",
{
create: false,
exclusive: false
},
function gotFileEntry(fe) {
$ionicLoading.hide();
$scope.imgFile = fe.toURL();
},
function(error) {
$ionicLoading.hide();
console.log("Error getting file");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Error requesting filesystem");
});
}
Adding <preference name="AndroidPersistentFileLocation" value="Compatibility" />to the config.xml made my folder & file visible. I hope this could help someone.
Now i can see the images, but all the images are Corrupt.
I am using fileDownload jQuery plugin to download a file which is served using ASP.NET MVC. The action is decorated with HttpGet and returns a FilePathResult. It works when a file is found. If a file is not found, I am not sure what to return in the action?
JavaScript:
function showMessageCancelDialog(message, request, titleValue) {
'use strict';
$('#messageDialog').html(message);
$('#messageDialog').dialog({
resizable: false,
width: '320px',
modal: true,
title: titleValue,
dialogClass: 'no-close',
buttons: {
Cancel: function () {
request.abort();
$(this).dialog("close");
}
}
});
}
function hideMessageDialog() {
'use strict';
$('#messageDialog').dialog("close");
}
function DownloadAttachment(itemId) {
'use strict';
var getAttachmentFileUrl = "/App/Download/GetAttachmentFile?ItemId=" + itemId;
var ajaxRequest = $.fileDownload(getAttachmentFileUrl, {
successCallback: function (message) {
hideMessageDialog();
},
failCallback: function (errorMessage) {
hideMessageDialog();
showMessageDialog("Download request failed:" + errorMessage, "Download attachment");
}
});
showMessageCancelDialog("Download in progress... , ajaxRequest, "Download attachment");
}
ASP.NET:
if(errorMessage == string.Empty)
{
this.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadFile);
return new FilePathResult(downloadFile, "application/octet-stream");
}
else
{
// WHAT DO I RETURN HERE?
}
You could throw an error with your errorMessage and the jquery function failCallback() should catch that.
else {
throw new HttpException(404, errorMessage);
}
this.Response.Clear();
this.Response.StatusCode = 500;
this.Response.ContentType = "text/html";
this.Response.Write(errorMessage);
throw new Exception(errorMessage);
The above code called the failCallback on javascript
I am trying to rename a file in phonegap, having followed their documentation. However the operation fails with "error code 1":
this.rename_file = function(current_name, current_dir, new_name, success_callback) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(current_dir + current_name, null, function (file_entry) {
fileSystem.root.getDirectory(current_dir, {create: true, exclusive: false}, function (dir_entry) {
alert(current_dir + current_name);
parent_entry = new DirectoryEntry(current_name, current_dir + current_name);
file_entry.moveTo(parent_entry, new_name, function () {
alert(new_name)
success_callback();
}, rename_fail);
}, rename_fail);
}, rename_fail);
}, rename_fail);
function rename_fail(error) {
alert("Error renaming file " + error.code);
}
};
Any ideas as to what the problem could be? Files exist, paths are correct.
I am using below code to select a video from library
navigator.camera.getPicture(function (data) {
callback(true, data);
},
function (e) {
callback(false, null);
}, {
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
mediaType: navigator.camera.MediaType.VIDEO
});
But in callback I am getting path in below format
content://media/external/video/media/832
How can I get the original file path?
I know its to late but maybe someone else needs this ( use resolveLocalFileSystemURL then toURL() )
check this code
navigator.camera.getPicture(onSuccess, onFail, {
limit: 1,
mediaType: window.Camera.MediaType.VIDEO,
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});
function onSuccess(fileURI) {
window.resolveLocalFileSystemURL(fileURI,
function (fileEntry) {
console.log(fileEntry.toURL());
//console.log(fileEntry.fullPath);
},
function () { });
}
function onFail(error) {
console.log(error);
}
step1
cordova plugin add cordova-filepath-resolver
For Ionic specifically, you can also use:
ionic plugin add cordova-filepath-resolver
step2
put this code
function camerasucess(videourl) {
//videourl is something like this content //media/external/video
var successCallback = function (data) {
console.log(JSON.stringify(data));
//here you will get the correct path of the video file and you can upload the video file
$scope.data = data;
};
var errorCallback = function (data) {
console.log(JSON.stringify(data));
};
window.FilePath.resolveNativePath(videourl, successCallback, errorCallback);
};
function cameraError(data) {
alert(JSON.stringify(data));
};
if (navigator.camera)
{
navigator.camera.getPicture(camerasucess, cameraError, {
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, mediaType: navigator.camera.MediaType.VIDEO,
});
}
When I try to write a file I am getting this error in Google Chrome:
Uncaught TypeError: Cannot read property 'root' of undefined FileSystemApi.html:29
onButtonSaveClick FileSystemApi.html:29
onclick
My sample code is as follows
var fileSys;
$(function () {
initFileSystem(onInitFileSystemSuccess);
});
function onInitFileSystemSuccess(fs) {
console.log('Opened file system: ' + fs.name);
fileSys = fs;
}
function onButtonSaveClick() {
alert('1');
var fileName = $("#fileName").val();
alert(fileName);
var fileContent = $("#fileContent").val();
alert(fileContent);
alert(fileSys.root);
fileSys.root.getFile(fileName, {
create: true,
exclusive: true
},
function (fileEntry) {
alert('2');
console.log('File opened: ' + fileEntry.fullPath);
fileEntry.createWriter(function (fileWriter) {
var blob = new Blob([fileContent], {
type: 'text/plain'
});
fileWriter.write(blob);
alert('done');
}, onFileSystemError);
}, onFileSystemError);
}
Would anyone be able to point out the problem(s), and, if so, contribute a solution?