Validate files using jquery file upload? - javascript

I am using jquery file upload as below.
dialogElem.find('#upload-image-file-input').fileupload({
url: url,
dataType: 'json',
autoUpload: true,
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) {
var fileCount = data.originalFiles.length;
if (fileCount > 5) {
alert("The max number of files is : "+5);
return false;
}
}).on('fileuploadprocessalways', function (e, data) {
//some logic
}).on('fileuploadprogress', function (e, data) {
//some logic
}).on('fileuploaddone', function (e, data) {
//some logic
}).on('fileuploadfail', function (e, data) {
//some logic
})
Inside fileuploadadd I added some validation logic. If the validation is failed, how can I stop all other events like fileuploadprogress,fileuploadfail and fileuploadprocessalways ?

If u have some task like i had few weeks ago - try this:
You can cancel an in-progress upload by aborting the XHR (ajax request) call.
You can bind to the fileuploadadd event of the file input field, submit the request while keeping the jqXHR object and use it for aborting:
jqXHR.abort();
For example:
$(".cloudinary-fileupload").bind('fileuploadadd', function(e, data) {
jqXHR = data.submit(); // Catching the upload process of every file
});
$('#cancel_button').click(function (e) {
if (jqXHR) {
jqXHR.abort();
jqXHR = null;
console.log("Canceled");
}
return false;
});
The following page includes some more code samples
https://github.com/blueimp/jQuery-File-Upload/issues/290
just call
if (fileCount > 5) {
jqXHR.abort();
jqXHR = null; }

jqXHR.abort() doesnt work for me. But throw aborts "add" handling:
.bind('fileuploadadd', function (e, data) {
if (total_uploads >= maxImagesPerPost){
throw new Error('Upload maximum reached');
}

Related

Jquery - Ajax : Unhandled multiple clicks event with ajax button "on Click method"

I have a button where i'm injecting an ajax request to a distant web service.
the traitment takes effects after checking a condition given from the success of another ajax request (thats why i am usung "ajaxSuccess")
My fonction looks like this :
$('body').on('click', '#btn', function (e) {
$(document).ajaxSuccess(function (event, xhr, settings) {
if (settings.url === window.annonce.route.testService) {
xhr = xhr.responseJSON;
var msg = {},
if (xhr == 1) { //case of traitement to be done
msg["attr1"] = attr1;
msg["attr2"] = attr2;
msg = JSON.stringify(msg);
console.log(msg);
$.ajax({
method: 'POST',
url: servicePostulation,
data: {msg: msg},
dataType: 'json',
success: function (data) {
console.log(data);
$("#btn").addClass("active");
},
error: function (data) {
console.log(data);
}
});
}
}
})
}
I my case , the "console.log(msg)" shows me a multiple sending of data msg , which means a multiple clicking events , and that's exactly the problem i wanna evitate,
i have tried many solutions with the " $('body').on('click') like :
e.stopImmediatePropagation();
e.preventDefault();
stopPropagation()
one()
off()
unbind()
but nothing works , so is there any further solution or explication ??
My suggest is to disable the button when user click and then enable the button when ajax complete.
**onClick:**
$('#btn').prop("disabled", true);
Ajax complete/success:
$('#btn').prop("disabled", false);

Reading files in JavaScript using the File API trhown "TypeError: e is undefined"

I'm trying to append files to FormData to handle files upload through AJAX and after read and keep finding for a solution without need to use external plugins I found this and I'm trying to use it on my code so I made this:
$(function () {
$('.smart-form').on('submit', function (e)
{
var files;
e.stopPropagation(); // Stop stuff happening
e.preventDefault(); // Totally stop stuff happening
if ($(".state-error").length < 1) {
// Create a formdata object and add the files
var data = new FormData();
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Grab the files and set them to our variable
files = e.target.files;
$.each(files, function (key, value)
{
data.append(key, value);
});
}
// Create a jQuery object from the form
$form = $(e.target);
// Serialize the form data
var formData = $form.serializeArray();
$.ajax({
async: false,
url: '{{ path('update-product', {'id': id}) }}',
type: 'POST',
data: formData,
cache: false,
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log("SUCCESS");
}
else
{
console.log("ERRORS");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log("ERRORS");
},
complete: function ()
{
// STOP LOADING SPINNER
}
});
}
});
});
But I'm getting this error at Firebug console:
TypeError: e is undefined
And I not able to find where is my mistake or what's happening. Here is a Fiddle with test code, can any help me and tell me what I'm doing wrong?
Update
The error is not the same at jsFiddle, if you take a look at Firebug console the error trown is this one instead:
TypeError: obj is undefined
length = obj.length,
Your problem is with this line:
files = e.target.files;
In the link you provided, he is attaching an event handler to the change event of the file input element, not the submit button:
document.getElementById('files').addEventListener('change', handleFileSelect, false);
So e.target would be the file input element and e.target.files would work.
You've changed the code around, and you're calling this in the submit button click handler. So e.target refers to the submit button, and e.target.files refers to nothing.
So change your code to this and it will work:
files = $('form #product_imageFile_file')[0].files;
See here for a working fiddle: http://jsfiddle.net/manishie/xyqoozb5/2/

Adding Request Headers to the XmlHttpRequest with Kendo UI Upload control

I'm trying to use the code provided by Telerik to add request headers to the XHR, but I'm getting the following error.
"0x800a139e - JavaScript runtime error: InvalidStateError"
Here is the code
$(document).ready(function () {
$("#file").kendoUpload({
multiple: false,
async: {
saveUrl: "save",
},
upload: onUpload,
});
});
function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function (e) {
if (xhr.readyState == 1 /* OPENED */) {
xhr.setRequestHeader("X-Foo", "Bar");
}
});
}
}
It turned out that Internet Explorer fires readystatechange twice with readyState 1 and the second execution of the handler causes the error. As a workaround for the the current case you could name the executed handler and unbind it after the first execution.
function onUpload(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onUploadReady(e) {
if (xhr.readyState == 1 /* OPENED */) {
xhr.setRequestHeader("X-Foo", "Bar");
xhr.removeEventListener("readystatechange", onUploadReady);
}
});
}
}

getting to grips with javascript callbacks - undefined callback data

My javascript skills are limited and I'm having a problem with the structure of a series of functions which I think need callbacks. I've been reading a number of posts and tutorials but it's not sticking...yet..
On my page I have a pop up modal which contains an image. If the user clicks the edit button it's to be edited in aviary. Once that's completed the image properties get saved into a database and then the images within the modal box - and the underlying form - should get updated with the edited image.
My series of events starts with the modal opening:
$('#editImageLink2').click(function(event) {
aviaryOnClick('image2', $(this).data('mode'), function(image) {
#do final bits here
});
});
Modal pops up then if the user clicks the edit button this next function starts the editor:
function aviaryOnClick(source, mode) {
editedImage = doAviary(source);
if (editedImage) {
return true;
} else {
return false;
}
}
So - aviary pops up as expected. Then when the user saves the edited image I'm starting to have trouble:
The doAviary function looks like this:
function doAviary(source) {
console.log("hit doAviary", source);
var featherEditor = new Aviary.Feather({
apiKey: 'XXXXXXXX',
apiVersion: 3,
theme: 'dark',
tools: 'all',
displayImageSize: true,
maxSize: 1200,
onSave: function(imageID, newURL) {
//replace image in modal preview
var img = document.getElementById(imageID);
img.src = newURL;
if (newURL != undefined) {
storeImage(newURL, updateFormImage(imageData));
featherEditor.close();
return true;
}
},
onError: function(errorObj) {
alert(errorObj.message);
return false;
}
});
return featherEditor.launch({
image: source,
url: $('#' + source).attr('src')
});
}
So I'm trying to run storeImage in the onSave event, which should then run a callback to the update images with the image data.
My storeImage function:
function storeImage(newURL, imageData) {
var options = new Object();
options.aviaryURL = newURL;
options.mode = mode;
options.dbID = ($('#dbID').val()) ? $('#dbID').val() : null;
//console.log("store image options object:", options);
jQuery.ajax({
url: '/filemanager/aviary',
type: 'POST',
dataType: 'json',
data: options,
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
console.log("finished store image", data);
$.cookie('asset_filename', data.image.filename);
$.cookie('asset_id', data.image.id);
imageData(data);
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
imageData(false);
}
});
so IF the image is saved the data should be passed back to the callback. If it fails it's false
Then in the update image function
function updateFormImage(data) {
if (data.result == 'success') {
image = data.image;
#simple updates of elements in page
}
}
My current problem is that on save I'm getting an error imageData is not defined - I'm not sure why this is - if it's waiting for ajax to complete before passing back the data to the callback it should exist.
Why does this error happen?
What better ways are there to refactor this code and use callbacks correctly.
I originally had a callback on the first function but got an error callback function not defined
Confused.
Thanks
imageData is not defined into doAviary.
Also, updateFormImage should return something (imageData).

FineUploader client event after all uploads are done

I implemented FineUploader and I would like to hook up my client script to an event after all files are uploaded. Is that possible?
My implementation follows. Just want to know if that's right direction.
function init() {
var uploader = new qq.FineUploader({
element: document.getElementById('button-selectfiles'),
request: {
endpoint: '/Up/UploadFile'
},
callbacks: {
onStatusChange: onFileUploadStatusChange
}
});
};
var uploads = 0;
function onFileUploadStatusChange(id, oldStatus, newStatus) {
console.log(newStatus);
if (newStatus === 'submitting') {
uploads++;
}
if (newStatus === 'upload successful' || newStatus === 'upload failed') {
uploads--;
}
if (uploads === 0) {
console.log('done');
}
}
onComplete - used for single upload file, if you are using a multiple files upload just use onAllComplete:
callbacks: {
onAllComplete: function() {
alert('done')
}
}
Your onFileUploadStatusChange function fails to check for cancelled files.
The way to verify if all files have been uploaded is via the API methods: getInProgress and getUploads. If we have 0 uploads in progress, and 0 failed uploads, then we can safely assume that all files have been uploaded. You may want to remove the check for failed uploads if you would still like to proceed if any upload has failed. We check for these conditions to be met during the onStatusChange and onComplete callbacks. The onStatusChange event should only check if the file has been cancelled because that might mean that all of the other files have completed, and thus the custom action can be completed.
Note: I've adapted my answer of 16989719 to work for non-jQuery Fine Uploader.
function init() {
var uploader;
function check_done() {
// Alert the user when all uploads are completed.
// You probably want to execute a different action though.
if (allUploadsCompleted() === true) {
window.alert('All files uploaded');
}
}
function allUploadsCompleted() {
// If and only if all of Fine Uploader's uploads are in a state of
// completion will this function fire the provided callback.
// If there are 0 uploads in progress...
if (uploader.getInProgress() === 0) {
var failedUploads = uploader.getUploads({ status: qq.status.UPLOAD_FAILED });
// ... and none have failed
if (failedUploads.length === 0) {
// They all have completed.
return true;
}
}
return false;
}
uploader = new qq.FineUploader({
element: document.getElementById('button-selectfiles'),
request: {
endpoint: '/Up/UploadFile'
},
callbacks: {
onStatusChange: function (id, oldStatus, newStatus) {
// This will check to see if a file that has been cancelled
// would equate to all uploads being 'completed'.
if (newStatus === qq.status.CANCELLED) {
check_done();
}
},
onComplete: check_done
}
});
};

Categories