Folder cant be seen in Gallery - javascript

I m creating a hybrid app using Ionic. I created a folder in my DCIM folder of android where I save downloaded Images, Gifs.
Here is my code :
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log("Root = " + fs.root.toURL() + "DCIM");
var entry=fs.root; entry.getDirectory("downloaded images", {create: true, exclusive: false},function (dirEntry) { },function (error) { }
);
}, function (error) {
});
});
Everything works fine. Only Problem is when I keep the foldername as "Downloaded_Images" or anything without space, I can see it in my android gallery , else the folder gets created but is not visible in gallery. But i need a folder with name "downloaded Images".

You could try something like this:
var yourDirectory = decodeURIComponent(fs.root + "downloaded%20images");

Related

Preloading all images using $ImageCacheFactory

I have created a mobile application using ionic framework.It contains many images.I need to load all the images with out flickering.So i used $ImageCacheFactory for preloading all the images by refering this blog.
I used below code.The problem is that app contains 100 png images,So i have to refer all the png files.
.run(function($ImageCacheFactory) {
$ImageCacheFactory.Cache([
"img/user.png",
"img/profile.png",
"img/logo.png",
"img/splash.png",
"img/map.png",
"img/shop.png",
"img/country.png",
"img/place.png"
]).then(function(){
console.log("Images done loading!");
},function(failed){
console.log("Error..!!!");
});
})
Is there any easy method for refering all the png images with single line code(All the images are in www/img folder).Thanks
Create an angular factory as follows
.factory("$fileFactory", function($q) {
var File = function() {};
File.prototype = {
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
});
Then to get list of all file using getEntries()
.run(function($ImageCacheFactory, $ionicPlatform, $fileFactory ) {
var fs = new $fileFactory();
$ionicPlatform.ready(function() {
fs.getEntries('img').then(function(result) {
var files = result;
files = files.unshift({
name: "[parent]"
}).map(function(i, v) {
return 'img/' + v.name;
});
$ImageCacheFactory.Cache(files).then(function() {
console.log("Images done loading!");
}, function(failed) {
console.log("Error..!!!");
});
})
});
});
You need to install dependencies Apache Cordova File
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
Reference : Helpful tutorial
Im sorry i dont have a n answer yet. But i know why it isnt working.
Using a Web Browser
Don't do it. If you even attempt to open this project in a web browser you're setting yourself up for failure. This application uses native device plugins that the web browser is unfamiliar with. In turn this will give strangeness and errors.

Jquery File Upload always fails with File Upload Aborted

I'm trying to get Blueimp's Jquery File Upload plugin working on my website, but for the life of me can't get it to upload files. I've been working on this all day and am stuck. It will upload the file and submit it to the UploadHandler class, but when it's trying to complete the handle_file_upload function it gets to:
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
but that always returns 0. I cannot figure out why the file won't upload. The full response I get back is:
{"files":[
{"name":"1397489968-32",
"size":0,
"type":"multipart\/form-data; boundary=----WebKitFormBoundaryrmi4L2ouOmB4UTVm",
"error":"File upload aborted",
"deleteUrl":"http:\/\/onceridden.demomycms.co.uk\/eshop\/library\/ajax\/?file=1397489968-32",
"deleteType":"DELETE"}
]}
ajax.file-upload.php only instantiates UploadHandler, nothing else.
If you'd like to see the full code you for UploadHandler you can download it from github, it's too big for me to post on here.
Can someone please tell me why the files won't upload? Yes I've done the basics such as checking the folder is CHMOD 777. I've tried this with various files of different types (they must be images to work, limited to jpg, png or gif) and sizes; all produce the same result.
As requested this is the JS file:
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '/eshop/library/ajax/ajax.file-upload.php',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#register-photo').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#register-files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#register-progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
It's pretty much the default file you get with the plugin with just the ID's changed to match my form.
Update
After much playing around and testing I have found out that the problem occurs when you change the name of the input from files to anything else. Why I have no idea. This is obviously an issue if you want to have it running on more than one input on a page...
I created a very simple version of the interface myself, and that does allow me to change the file name, so it must be something to do with the example they use. I would like to be able to use preview images and the such (something I couldn't figure out in my simple test) so I need to solve this issue.
This is in case anyone else ever gets stuck on this problem as well. The issue is caused by the paramName option, which if not set takes it's value from the input name. It's not set by default, so when changing the input name I was also changing paramName, meaning it no longer matched the variable coming back from the UploadHandler class.
The solution is to add paramName: 'files[]' as an option.
I was facing same issue(action aborted) and have different answer.
The folder/directory where I was uploading file did not have permission to upload file.
on Linux server you can run following command
chmod 777 files
When I gave permission to this directory, I did not get this error, and could upload file successfully.
I am running a centOS 6.9. chmod 0755 /server/php/files (rather than 777) and I changed the ownership (chown) over to apache. Ta-Da!

phonegap - cross platform way of getting default music folders on smartphones

im trying to get the default music folders for all phonegap supported platforms. basically i can download and save file on the sdcard using the function below. but i want to add code to detect platform and give me default music folders for platform so as i can save mp3 file there.
function downloadFile(remoteloc,new_name,userid,mid,errorbox,origname)
{
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html","");
var fileTransfer = new FileTransfer();
fileEntry.remove();
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"progress progress-danger progress-striped\"><div id='id_p' class=\"bar\" style=\"width: 5%\"></div></div>");
fileTransfer.onprogress = function(progressEvent)
{
if (progressEvent.lengthComputable) {
$('#id_p').css('width',Math.ceil((progressEvent.loaded / progressEvent.total)*100)+"%");
} else {
}
}
fileTransfer.download(
remoteloc,
sPath + new_name,
function(theFile) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-info fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Complete. Added to Media Player</div>"
+"<div>Play Song</div>"+"<br/>"+theFile.toURI());
//update the database field to show file has been transfered
if (!isOnline())
{
$('#error_box').html("<div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Sorry but you seem to be offline.</div>");
return;
}
var request={'controller':'music','action':'updatedownload','userid':userid,'mid':mid};
queryAPI(request,function (d){
//check result and set local storage variables
if (d.success>0)
{
} else
{
}
localStorage.removeItem('resume');
window.key=false;
//setTimeout(function () {$('#'+errorbox).html("<div>"+origname+"</div>");},3000);
});
},
function(error) {
$('#'+errorbox).html("<div>"+origname+"</div><div class=\"alert alert-error fade in\"><button class=\"close\" data-dismiss=\"alert\"><span class=\"awe-remove-circle\"></span></button>Download Error! Error code:"+error.code+"</div>");
}
);
},
fail);
},
fail);
}
Because of major platform differences, there isn't a "one time getDirectory call" solution to do this.
The best way to handle this is to do a check for the platform you're currently running and write the file based on that.
var platform = device.platform;
switch(platform)
{
case 'iPhone':
//save to the app document folder
break;
case 'Android':
//save to <external_storage_root>/Music
break;
case 'BlackBerry':
//Save to /SDCard/BlackBerry
break;
}
Be sure to check official documentation for the right file path's etc.
Also take note that while /var/root/Media/iTunes_Control/Music is sometimes mentioned as the default folder for music on iOS, it's managed by iTunes so it can be modified at any time and is only useful for temporary storage if it can be accessed at all. Using the documents folder is the prefered method.

PhoneGap attempting to upload audio media file - works iOS, file cannot be found Android

We have an app that records audio, making use of the PhoneGap Media API and in iOS's case the File API.
When the user clicks the Accept & Upload button, the app moves that file to the server making use of PhoneGap's File.FileTransfer() method.
Works well with iOS, Android not so much.
When I connect my Android device to my computer and mount as a drive, I can see that the file is getting created at the root which is where it should be.
After the audio file has been created, I'm able to play the file on my device from the location stored in the global var fullRecordPath which = recording.wav
When I attempt to point File.FileTransfer() at that came path I'm getting Error Code = 1 which I understand is File Not Found
Code Handling the Accept & Upload tap event:
$('#btnAcceptUpload').live('tap',function () {
if(isIOS){
thisFileToUpload = fullRecordPath;
} else {
// thisFileToUpload = './'+fullRecordPath; //doesn't work
// thisFileToUpload = 'file:///'+fullRecordPath; //doesn't work
thisFileToUpload = fullRecordPath; //doesn't work
}
var options = new FileUploadOptions();
msg = '';
options.fileKey="file";
msg += "options.fileKey = "+options.fileKey+"\n";
options.fileName=thisFileToUpload.substr(thisFileToUpload.lastIndexOf('/')+1);
msg += "options.fileName = "+options.fileName+"\n";
options.mimeType='audio/wav';
options.chunkedMode = false;
msg += "options.mimeType = "+options.mimeType+"\n";
msg += "thisFileToUpload = "+thisFileToUpload;
alert(msg);
var ft = new FileTransfer();
ft.upload(thisFileToUpload, "http://10.0.17.121/~email/ttmovefiles.php", fileUploadSuccess, fileUploadFailure, options);
});
Success Callback:
function fileUploadSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
Failure Callback:
function fileUploadFailure(error){
alert("An error has occurred: Code = " + error.code);
}
Thanks for looking.
Alright, alright. I figured this one out. I promise I'll come back through and tighten this one down later, but wanted to get it documented so I might end helping another.
in iOS to create a new piece of media you have no choice, you gotta use the File api. This same fully qualified spot in the filesystem was moved in to the same global var which the Media.play() method played nicely with... in iOS.
Not sure why it works this way, but with Android, Media.play() doesn't like the fully qualified path passed in to it. It just wants the filename and it apparently searches from the root.
File.FileTransfer.upload() always wants the fully qualified path of the asset to upload, regardless iOS or Android.
To Make this work:
I used the File API to create the file that the audio Media then uses to move the recording in to. I set 2 global vars: one for playing the audio on the device fullRecordPath and the other for uploading fullUploadPath.
Here's the function the creates the file, invokes the media API and sets the global vars that Android wants:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile(recordFileName, {
create: true,
exclusive: false
}, function(fileEntry){
alert("---------> Android File " + recordFileName + " created at " + fileEntry.fullPath);
fullRecordPath = recordFileName;
fullUploadPath = fileEntry.fullPath;
mediaVar = new Media(recordFileName, function(){
alert("Android media created successfully");
}, androidMediaCreateFailure, mediaStatusCallback); //of new Media
onMediaCreated();
}, androidMediaCreateFailure); //of getFile
}, androidMediaCreateFailure); //of requestFileSystem
Here's the code to play that media back
function playAudio() {
var my_media = new Media(fullRecordPath,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err.code);
exposeObject(err);
});
my_media.play();
}
Here's the code to upload
$('#btnAcceptUpload').live('tap',function () {
if(isIOS){
thisfullUploadPath = fullRecordPath;
} else {
thisfullUploadPath = fullUploadPath;
}
var options = new FileUploadOptions();
msg = '';
options.fileKey="file";
msg += "options.fileKey = "+options.fileKey+"\n";
options.fileName=thisfullUploadPath.substr(thisfullUploadPath.lastIndexOf('/')+1);
msg += "options.fileName = "+options.fileName+"\n";
options.mimeType='audio/wav';
options.chunkedMode = false;
msg += "options.mimeType = "+options.mimeType+"\n";
msg += "thisfullUploadPath = "+thisfullUploadPath;
alert(msg);
var ft = new FileTransfer();
ft.upload(thisfullUploadPath, "http://10.0.17.121/~email/ttmovefiles.php", fileUploadSuccess, fileUploadFailure, options);
});
On android you need to resolveFileSystem
window.resolveLocalFileSystemURI(FILEURI, function(msg){
// success call msg.fullPath
}, function(){
// FAIL
});

Uploadify and flash issue uploading to remote server

I'm trying to use uploadify to upload images to a remote server. I've have done everything I can think of for the cross scripting issue or whatever.
Here is what i've done.
scriptAccess to 'Always' in the uploadify function.
I have a crossdomain.xml on my ww2 server with uploadify.swf in the root as well.
I have uploaded my javascript jquery lib file to the remote ww2 server and put it in the header
I put the jquery.uploadify.js and the swfobject.js in the root directory as well.
If I try to click the X to cancel a file I get the error: Error calling method on NPObject
Or uploads don't work either.
If anyone can help with this that would be great. If there are any other good flash based or non flash based multi uploaders that will do remote files with no issue please let me know.
Thanks
I managed to figure it out on my own. I will answer it just incase someone else might have this issue because there is very little help even on the authors site for it.
I decided to leave the Flash file on the same server(Web server) because it didnt seem to work putting it on the media server with the javscript files. The js wouldn't work.
So my main server has the uploadify folder still on the server and I only put the php files(uploader.php) I needed to process my images on the media server AND the crossdomain.xml in the root of that server.
Then told uploadify in the parameter settings to point to my uploader.php script on that server.
Everything worked like a charm after that. I took quite a while to figure it out and get passed the errors. Now I can load balance my media.
Hope this helps someone else. Uploadify is a really nice multi file uploader.
You need to change code in your uploadify.js:
/* Original code */
uploadifyCancel:function(ID) {
jQuery(this).each(function() {
document.getElementById(jQuery(this).attr('id') + 'Uploader').cancelFileUpload(ID, true, true, false);
});
},
/*New code */
uploadifyCancel:function(ID){
jQuery(this).each(function(){
document.getElementById(jQuery(this).attr("id")+"Uploader").cancelFileUpload(ID,true,false)
});
},
/*Original code */
jQuery(this).bind("uploadifyComplete", {
'action': settings.onComplete
}, function(event, ID, fileObj, response, data) {
if (event.data.action(event, ID, fileObj, unescape(response), data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(' - Completed');
if (settings.removeCompleted) {
jQuery("#" + jQuery(event.target).attr('id') + ID).fadeOut(250,function() {
jQuery(this).remove()
});
}
jQuery("#" + jQuery(event.target).attr('id') + ID).addClass('completed');
}
});
/* New code */
jQuery(this).bind("uploadifyProgress", {
'action': settings.onProgress,
'toDisplay': settings.displayData
}, function(event, ID, fileObj, data) {
if (event.data.action(event, ID, fileObj, data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID + "ProgressBar").animate({
'width': data.percentage + '%'
},250,function() {
if (data.percentage == 100) {
jQuery(this).closest('.uploadifyProgress').fadeOut(250,function() {
jQuery(this).remove()
});
}
});
if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%';
if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s';
if (event.data.toDisplay == null) displayData = ' ';
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(displayData);
}
});

Categories