Renaming files in Phonegap - 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.

Related

Download progress bar pops and ends up, with no errors and no output file in the device

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.

Session state not working in ashx file on server

I have a session issue, where my handler is not reading the session values. This ONLY occurs on our server. When I run local, it works fine. I'm also calling IRequiresSessionState, so that shouldn't be an issue either.
I'm able to see the session state is still working up until I call my ashx file. Inside this file however, the session is lost, according to my trace.
Here's my javascript code I use to call my handler:
$(document).ready(function () {
$("#<%=btnAdd.ClientID%>").uploadify({
'uploader': '../Scripts/Uploadify/uploadify.swf',
'script': '../Handlers/file1.ashx?mode=schedule',
'cancelImg': '../Images/cancel.png',
'wmode': 'transparent',
'hideButton': true,
'fileExt': '*.XML;*.xml;*.CIF;*.cif;*.zip;*.ZIP',
'fileDesc': 'Schedule Files',
'onComplete': function (event, queueID, fileObj, response, data) {
$('#pnlOverlayFrame').show();
document.getElementById("<%=hdnFilePath.ClientID%>").value = response;
},
'onAllComplete': function (event, queueID, fileObj, response, data) {
$get('<%= hdnDirty.ClientID %>').value = '0';
// document.getElementById('<%= btnConfirm.ClientID %>').click();
document.getElementById('<%= btnUploadFiles.ClientID %>').click();
}
,
'multi': true,
'expressInstall': '../Scripts/Uploadify/expressInstall.swf'
});
Below is my handler .cs file code
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
if (context.Session != null && context.Session["CurrentDirectory"] != null)
{
StorageRoot = context.Server.MapPath(context.Session["CurrentDirectory"].ToString());
}
else
{
//string DirectoryName = "OP1" + "_" + DateTime.Now.ToString().Replace('/', '_').Replace(':', '_').Replace(' ', '_') + Guid.NewGuid().ToString();
string DirectoryName = "OP1" + "_" + String.Format("{0:yyyyMdHHmmss}", DateTime.Now) + Guid.NewGuid().ToString();
//DirectoryName = DirectoryName.Remove(DirectoryName.Length - 3, 3);
HttpContext.Current.Session.Add("CurrentDirectory", DirectoryName);
//context.Session["CurrentDirectory"] = DirectoryName;
StorageRoot = context.Server.MapPath(DirectoryName);
}
string filename = postedFile.FileName;
if (!Directory.Exists(StorageRoot))
Directory.CreateDirectory(StorageRoot);
postedFile.SaveAs(StorageRoot + #"\" + filename);
context.Response.Write(StorageRoot);
context.Response.StatusCode = 200;
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
Every time it goes in else part and create new folder as per code.
Please advice
I got the alternate way of handling session in ASJX file
i have pass session in 'scriptData': { 'SessionData': currentDirectory }, tag in to uploadify function and get this data in term of Form
JavascriptCode
var currentDirectory = "";
$(document).ready(function () {
$("#<%=btnAdd.ClientID%>").uploadify({
'uploader': '../Scripts/Uploadify/uploadify.swf',
'script': '../Handlers/file1.ashx?mode=schedule',
'scriptData': { 'SessionData': currentDirectory },
'cancelImg': '../Images/cancel.png',
'wmode': 'transparent',
'hideButton': true,
'fileExt': '*.XML;*.xml;*.CIF;*.cif;*.zip;*.ZIP',
'fileDesc': 'Schedule Files',
'onComplete': function (event, queueID, fileObj, response, data) {
$('#pnlOverlayFrame').show();
document.getElementById("<%=hdnFilePath.ClientID%>").value = response;
currentDirectory = response;
$("#<%=btnAdd.ClientID%>").uploadifySettings('scriptData', { 'SessionData': currentDirectory });
},
'onAllComplete': function (event, queueID, fileObj, response, data) {
$get('<%= hdnDirty.ClientID %>').value = '0';
// document.getElementById('<%= btnConfirm.ClientID %>').click();
document.getElementById('<%= btnUploadFiles.ClientID %>').click();
currentDirectory = "";
}
,
'multi': true,
'expressInstall': '../Scripts/Uploadify/expressInstall.swf'
});
we have set session data in onComplete event with use of below line
$("#<%=btnAdd.ClientID%>").uploadifySettings('scriptData', { 'SessionData': currentDirectory });
and get data in c# like below
string sessionValue = Convert.ToString(context.Request.Form["SessionData"])

Opening a PDF in cordova javascript

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.

plugin plupload not uploading multiples file in single selection

Below is mine Js Code.Multiple file selection working fine if I call FilesAdded event inside init method.but when I try to bind FilesAdded event to plupload object i.e uploader only first image file get uploaded to server rest discarded.
<script type="text/javascript">
// Custom example logic
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: 'Home/Upload',
flash_swf_url: 'Scripts/Moxie.swf',
silverlight_xap_url: 'Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
init: {
PostInit: function () {
document.getElementById('filelist').innerHTML = '';
},
UploadProgress: function (up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
uploader.bind('FilesAdded', function () {
uploader.start();
});
</script>
Any help would be appreciated
put the below code after 'FilesAdded' event
uploader.bind('Error', function (up, err) {
console.log(err);
});
check the error code in console so that you can debug accordingly.

HTML5 File System API error "Cannot read property 'root' of undefined"

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?

Categories