uploadify : restrict image dimension - uploadify

I am using Uploadify to upload image in php(codeigniter). Tested with the sample php file that come with the uploadify package. It works. However, I can't get onUploadError triggered. The sample php code has:
if (in_array($file_ext,$fileTypes)) {
$newFileName = mt_rand() . time() . '.' . $file_ext;
$targetFile = rtrim($targetPath,'/') . '/' . $newFileName;
move_uploaded_file($tempFile,$targetFile);
echo $newFileName;
} else {
echo 'Invalid file type.';
}
js is very simple as following:
$('#file_upload').uploadify({
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.jpeg; *.png',
'swf' : '/static/uploadify/uploadify.swf',
'uploader' : '/static/uploadify/uploadify.php',
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
console.log('The file ' + file.name + ' errorCode ' + errorCode + ' errorMsg ' + errorMsg + ' errorString ' + errorString);
},
'onUploadSuccess' : function(file, data, response) {
console.log(data);
}
});
when the Invalid file type. is echoed to the frontend. the onUploadSuccess is triggered instead of onUploadError. It seems odd to me that there is no indicator to stell uploadify there is an error from php.
the only way that triggers onUploadError is to set a non 200 http header before echoing. however, onUploadError function arguments errorCode, errorMsg, errorString are the http code and the echo content(error message) is lost.
UPDATES
I modified the question title so it speaks the real problem I was trying to solve. And I have since found the solution.

I finally got sometime to tackle this problem and here are my steps to solve it.
first, the problem of onUploadError is not fired is because the file has been uploaded successfully
second, uploadify queue limit and upload limit are updated accordingly upon successful upload regardless of detection of wrong image dimension from the backend.
So the solution is that my backend checks image dimension and responds with a json data with error message which shown to user. also reset uploadify, really it is swfupload, variable successful_uploads. that makes sure the queuelimit or upload limit not messed up. sample code:
'onUploadSuccess' : function(file, data, response) {
var obj = eval('(' + data + ')');
if ( obj.success ) { alert('uploaded') }
else {
var stats = this.getStats();
this.setStats({successful_uploads: stats.successful_uploads - 1});
}
}
see swfupload setStats method http://demo.swfupload.org/Documentation/#setStats

Related

i'm using resumable js to upload video on JWPlayer in laravel wepapp

i'm using resumable js to upload video on JWPlayer in laravel wepapp. when i upload video. it uploads only first chunk of video on jwp dashboard then return below error in network tab.
a:4:{s:6:"status";s:5:"error";s:7:"message";s:72:"Uploads for the media files with the status `processing` are not allowed";s:4:"code";s:16:"PermissionDenied";s:5:"title";s:17:"Permission Denied";}
since last two i'm looking for solution. see below my resumable js code. i passed 1mb chunk on jwp server to store. but after first chunk it says "Uploads for the media files with the status processing are not allowed" as i mentioned full error message above.
var $ = window.$; // use the global jQuery instance
var $fileUpload = $('#resumable-browse');
var $fileUploadDrop = $('#resumable-drop');
var $uploadList = $("#file-upload-list");
if ($fileUpload.length > 0 && $fileUploadDrop.length > 0) {
console.log($fileUpload.data('url'));
var resumable = new Resumable({
// Use chunk size that is smaller than your maximum limit due a resumable issue
// https://github.com/23/resumable.js/issues/51
chunkSize: 1 * 1024 * 1024,
// 1MB
method: "POST",
simultaneousUploads: 1,
testChunks: false,
throttleProgressCallbacks: 1,
// Get the url from data-url tag
target: $fileUpload.data('url'),
headers: {
"X-Session-Id":$("#jwToken").val(),
},
// Append token to the request - required for web routes
query: {
_token: $('input[name=_token]').val()
}
}); // Resumable.js isn't supported, fall back on a different method
if (!resumable.support) {
$('#resumable-error').show();
} else {
// Show a place for dropping/selecting files
$fileUploadDrop.show();
resumable.assignDrop($fileUpload[0]);
resumable.assignBrowse($fileUploadDrop[0]); // Handle file add event
resumable.on('fileAdded', function (file) {
// Show progress pabr
$uploadList.show(); // Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show(); // Add the file to the list
$uploadList.append('<li class="resumable-file-' + file.uniqueIdentifier + '">Processing <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName); // Actually start the upload
resumable.upload();
});
resumable.on('fileSuccess', function (file, message) {
// Reflect that the file upload has completed
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(completed)');
});
resumable.on('fileError', function (file, message) {
// Reflect that the file upload has resulted in error
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')');
});
resumable.on('fileProgress', function (file) {
// Handle progress for both the file and the overall upload
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html(Math.floor(file.progress() * 100) + '%');
$('.progress-bar').css({
width: Math.floor(resumable.progress() * 100) + '%'
});
});
}
}
/***/ }),
I'd make sure when you created the video that you specified the multipart upload method.
Also make sure the location you're trying to upload to is the one returned in the create call (it should be going to the /v1/videos/upload/resumable endpoint). This guide should give more details about the process.

How do youshow remote Images using Titanium.Media.openPhotoGallery

I want to show my remote images (coming from web service or remote URL). the default images shown in kitchensink app, are the saved Photos. I want to place the remote URL photos instead of Saved photos. Please anyone explain it that what changes I can make using Titanium.Media.openPhotoGallery This is example code for kitchensink app.
Titanium.Media.openPhotoGallery({
success : function(event) {
var cropRect = event.cropRect;
var image = event.media;
// set image view
Ti.API.debug('Our type was: ' + event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
imageView.image = image;
} else {
// is this necessary?
}
Titanium.API.info('PHOTO GALLERY SUCCESS cropRect.x ' + cropRect.x + ' cropRect.y ' + cropRect.y + ' cropRect.height ' + cropRect.height + ' cropRect.width ' + cropRect.width);
},
cancel : function() {
},
error : function(error) {
},
allowEditing : true,
popoverView : popoverView,
arrowDirection : arrowDirection,
mediaTypes : [Ti.Media.MEDIA_TYPE_VIDEO, Ti.Media.MEDIA_TYPE_PHOTO]
});
Unfortunately I don't think you can load in remote images with openPhotoGallery. This method is only for device photo library access.
You will probably have to make a window that looks the same yourself and load in the images through imageView or xhr call.

JQuery Ajax function now working

I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.

POSTing file information via ajax after upload using PlUpload

I'm using a customized example of plupload, where
one or more files are first uploaded to an Amazon S3 bucket, and
then file info + user-entered data (e.g. description) is POSTed
via ajax to my controller action in a loop.
This controller action then verifies that the file was upload to the S3 bucket and then saves the info into the database, returning a success or failure to the ajax call.
I use the 'UploadComplete' event to check for any upload errors, and if there are none, perform the actual POSTs in a loop.
What I'd like to do is wait until the entire loop has finished processing and then display the confirmation message (all success, all failed, mix of both) accordingly.
Current code:
uploader.bind('UploadComplete', function (up, files) {
var errorsPresent = false;
var errors = '';
// re-enable buttons
$('div.plupload_buttons a').removeClass('disabled');
$.each(uploader.files, function (i, file) {
if (errorDescArray.hasOwnProperty(file.id)) {
errorsPresent = true;
errors += errorDescArray[file.id] + '<br />';
}
else if (file.status = plupload.DONE) {
var jqXhr = $.post('/documents/add', {
'__RequestVerificationToken': $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
'filename': file.name,
'size': file.size,
'location': $('#' + file.id + '_location').val(),
'description': $('#filedesc_text_' + file.id).text()
}).error(function (response) {
errorsPresent = true;
errors += response.responseText + '<br />';
});
}
});
//
if (errorsPresent) {
$('#uploadErrors').html('<div data-alert="alert" class="alert-message block-message fade in error">×<p>' + errors + '</p></div>');
}
else {
// set confirmation message
var message = files.length + ' file(s) were successfully uploaded.';
// clear file list
$('ul.plupload_filelist').html('');
// remove files from list
uploader.splice();
// hide modal
$('#upload-modal').modal('hide');
// show confirmation
$('#flashMessage').html('<div data-alert="alert" class="alert-message block-message fade in success">×<p>' + message + '</p></div>');
}
});
The above is obviously flawed in that the second half of the snippet doesn't really wait for the POSTs to complete, with the result that the success confirmation is displayed even if POST has an error response.
So my question is this: How do I perform an ajax post in a loop (unless there's a better way) and process the confirmation message after the loop has finished processing?

Uploadify: show error message from HTTP response

If the server returns an error (HTTP response code != 200) when uploading a file with Uploadify, the uploaded file gets a red background and a message is show like this:
file.jpg (52.78KB) - HTTP Error
indicating that there was a HTTP Error. But that's not very useful to the the user. How can I make it show a more detailed error message? Like: 'Not a valid image' or 'Quota full'?
I was thinking of passing those messages in the HTTP response body, but Uploadify doesn't pick them up. Is there a known way to pass error messages back to Uploadify?
Take a look at these two posts in the uploadify forum on how to handle errors
onError to display what's happening
and
Upload script error reporting
there is a lot of useful info in there ..
Update
The following seems to do the trick for me ..
'onComplete': function(a, b, c, d, e){
if (d !== '1')
{
alert(d);
}
else
{
alert('Filename: ' + c.name + ' was uploaded');
}
}
coupled with this version of the uploadify script
<?php
if (!empty($_FILES))
{
$tempFile = $_FILES['userfile']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['userfile']['name'];
move_uploaded_file($tempFile,$targetFile);
switch ($_FILES['userfile']['error'])
{
case 0:
$msg = ""; // comment this out if you don't want a message to appear on success.
break;
case 1:
$msg = "The file is bigger than this PHP installation allows";
break;
case 2:
$msg = "The file is bigger than this form allows";
break;
case 3:
$msg = "Only part of the file was uploaded";
break;
case 4:
$msg = "No file was uploaded";
break;
case 6:
$msg = "Missing a temporary folder";
break;
case 7:
$msg = "Failed to write file to disk";
break;
case 8:
$msg = "File upload stopped by extension";
break;
default:
$msg = "unknown error ".$_FILES['userfile']['error'];
break;
}
}
if ($msg)
{ $stringData = "Error: ".$_FILES['userfile']['error']." Error Info: ".$msg; }
else
{ $stringData = "1"; } // This is required for onComplete to fire on Mac OSX
echo $stringData;
?>
Unfortunately the onUploadError event does not have access to the reponse body. You'll have to return 200 status and handle the errors in onUploadSuccess as far as I'm aware.
Here's how I'm doing it:
'onUploadSuccess' : function(file, data, response) {
var responseObj = JSON.parse(data);
if(responseObj.error_message)
{
$("#" + file.id).hide(); // this will hide the misleading "complete" message..
alert(responseObj.error_message);
return;
}
}
Or better yet you could replace the "complete" message with your error message like so:
'onUploadSuccess' : function(file, data, response) {
var responseObj = JSON.parse(data);
if(responseObj.error_message)
{
$("#" + file.id).find('.data').css('color', 'red').html(' - ' + responseObj.error_message);
return;
}
console.log(file, data, response);
}
I've had the same problem. after search for hours I found the problem. I have set "proxy server" in my "internet Options->Lan setting" , and when I returned it to default state, uploadify worked again.
For uploadify version 3.0+ take a look at the onUploadSuccess option - specifically the passed in variable named data - that will have whatever the server echoed. If you echo JSON remember to decode it like so:
...
'onUploadSuccess' : function(file, data, response) {
if (response){
var json_data=JSON.decode(data);
/* code here */
}
},
....

Resources