plugin plupload not uploading multiples file in single selection - javascript

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.

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.

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.

Renaming files in Phonegap

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.

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?

plupload statechange even plupload.STARTED not working

I am trying to make plupload work from the jsfiddle sample jsfiddle-plupload
but that is not working on my side, the statechange events if block is getting skipped below is code
function validClasses()
{
datas=[];
$('#uids li').each(function() {
var data = {
className: $(this).attr("id")
};
datas.push(data);
});
if(datas.length>0)
{
return true;
}else{
alert('error');
return false;
}
}
var uploadInitialized = false;
function plupload(){
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,html4',
url: 'fileUpload.htm',
max_file_size: '200mb',
chunk_size: '1mb',
unique_names: true,
multiple_queues: true,
multipart_params: {
"name": $("#name").val()
},
// Specify what files to browse for
filters: [
{
title: "Image files",
extensions: "jpg,gif,png,eps,jpeg,pdf,tiff,tif"},
{
title: "Zip files",
extensions: "zip"}
],
init: {
StateChanged: function(up) {
if (!uploadInitialized && up.state == plupload.STARTED) {
if (!validClasses()) {
up.stop();
} else {
uploadInitialized = true;
}
}
},
BeforeUpload: function(up, file) {
up.settings.multipart_params = {'name': $('#name').val()}
}
}
});
}
please note that in jsfiddle sample, the upload is just stopped, that is i can upload without adding files again. Where as on my side, the start upload button is getting disappeard, the file is in list but buttons disappear. and i am getting the upload status in place of buttons, i want the buttons to be there if upload is stopped also. I means in StateChanged i directly wrote up.stop() and that is also not working. Anyone please help. Thanks.

Categories