Uploadifive -- onQueueComplete Not Working Correctly; Options to Limit Queue and File Sizes Also Not Working - uploadify

I am using Uploadifive to handle file uploads. My (extremely standard) configuration is as follows:
<form>
<div id="queue"></div>
<div ><input id="file_upload" name="file_upload" type="file" multiple="true"></div>
<div class="uploadifive-button">Upload Files</div>
</div>
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadifive({
'auto' : false,
'checkScript' : 'check-exists.php',
'formData' : {'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'queueID' : 'queue',
'removeCompleted' : true,
'queueSizeLimit' : 10,
'uploadLimit' : 0,
'uploadScript' : 'uploadifive.php',
'onUploadComplete' : function(file, data) {function goes here}, 'onQueueComplete' : function() { location.reload(); }
});
});
</script>
I've got 2 problems:
The options for uploadLimit and queueSizeLimit don't seem to work. I can only upload 2 files at a time. If I upload more than 2, the upload works, but I get a lot of popups (generated from check-exists.php) saying the file already exists on server, do I want to replace it.
The onQueueComplete function seems to run for each file upload, rather than once after all uploads are complete. I.e., if I'm uploading 10 files, the page refreshes 10 times.
I'm running the latest version of Firefox, I'm using jquery version 1.4.4, and Firebug reports no problems.
Any help appreciated.

Probably to late to answer this question, but it could help someone else. I got my way around file upload size limit by using 'onAddQueueItem' event. Here is the code snippet.
var bytesLoaded = 0;
$("#file_upload").uploadifive({
....
'onAddQueueItem' : function(file) {
bytesLoaded += file.size;
//setting maximum upload to 20MB
if(bytesLoaded > (20*1024*1024)){
alert"The file uploaded is greater than 20MB.");
cancel(); //cancel button ensures the upload is not done
}
}
});

Related

How to display error message of jquery dropzone

I use dropzone with CI, i don't know how to display error message and custom message when upload false, this is my script
Dropzone.autoDiscover = false;
try {
var myDropzone = new Dropzone("#adminform" , {
paramName: "filename", // The name that will be used to transfer the file
maxFilesize: 0.5, // MB
url: window.location.href,
addRemoveLinks : true,
dictDefaultMessage :
'<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i> Drop files</span> to upload \
<span class="smaller-80 grey">(or click)</span> <br /> \
<i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>',
dictResponseError: 'Error while uploading file!',
//change the previewTemplate to use Bootstrap progress bars
previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n <div class=\"dz-success-mark\"><span></span></div>\n <div class=\"dz-error-mark\"><span></span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
});
}
catch(e) {
alert('Dropzone does not support older browsers!');
}
And PHP return 400:
$this->output->set_header("HTTP/1.0 400 Bad Request");
But when i hover image it's display [object Object] but message is:
dictResponseError: 'Error while uploading file!'
For anyone in need:
You can return a response message from the server using echo. Then in the js code add an error event handler
PHP
header("HTTP/1.0 400 Bad Request");
echo "Ups error message";
JS
this.on('error', function(file, response) {
$(file.previewElement).find('.dz-error-message').text(response);
});
For me this code finally worked, used as a dropzone option:
error: function(file, message) {
$(file.previewElement).addClass("dz-error").find('.dz-error-message').text(message.Message);
}
I used message.Message since the ASP.net WebAPI returns a JSON object, but not with the required "error" key.
You can simply echo back the message from server via PHP file
if($file_uploaded == true)
{
//perform operations on valid upload
} else {
//upload failed, echo back negative response to dropzone.js
$this->output->set_header("HTTP/1.0 400 Bad Request");
echo "Error uploading file";
}
While your HTML file can look like:
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "icon_image", // The name that will be used to transfer the file
maxFilesize: 2, // MB
init: function() {
this.on("error", function(file, response) {
// do stuff here.
alert(response);
});
}
};
</script>
Hope it helps :)

Laravel Dropzone Invalid Argument

i get a invalid argument in my controller when i post my form including images via dropzone.js. I set the param name to files and it is working without dropzone. i can't figure out why i get a invalid argument error while using dropzone. can anyone help?
Script
<script>
Dropzone.options.dropkicks = {
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
paramName: "files",
maxFiles: 100
}
var myDropzone = new Dropzone("div#dropkicks", { url: "item-create-post"});
</script>
Controller
foreach(Input::file('files') as $file) {
$filename = time(). $file->getClientOriginalName();
$uploadflag = $file->move('uploads', $filename);
if($uploadflag) {
$uploadedfiles[] = $filename;
$item_image = ItemImage::create(
array(
'item_id' => $item->id,
'image' => $filename
)
);
}
}
Dropzone
<div class="dropzone" id="dropkicks"></div>
There's no easy way to do this unless you mess with the source code of dropzone.js. That's because the plugin is meant to be used to upload files asynchronously. With a couple of changes in dropzone.js though, you can get it to work (I'm assuming you're using the latest version).
Find this line:
document.body.appendChild(_this.hiddenFileInput);
And replace it with this:
_this.hiddenFileInput.setAttribute("name", "files[]");
_this.element.appendChild(_this.hiddenFileInput);
Also find this line:
return setupHiddenFileInput();
And comment it out:
// return setupHiddenFileInput();
You form should look something like this:
<!-- Make sure you add enctype="multipart/form-data" to the form tag -->
<form action="/item-create-post" method="post" enctype="multipart/form-data">
<!-- some form fields... -->
<div class="dropzone" id="dropkicks"></div>
<!-- maybe some more form fields... -->
<button type="submit">Submit Form</button>
</form>
Your script part should also look like this:
Dropzone.options.dropkicks = {
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
paramName: "files",
maxFiles: 100,
// This URL is not really used in your case but it's needed
// because the plugin won't attach itself without one specified
url: '#'
}
Also remove this line from your script because it's not needed. The dropzone will automatically be attached to any elements with the class "dropzone":
var myDropzone = new Dropzone("div#dropkicks", { url: "item-create-post"});
Place the script right below where you've included main dropzone.js.

File Upload with Ajax And Spring Secruity

After upgrading Spring Security to the 3.2.x version, the Ajax file upload function in my application is no longer working. Based on the SS 3.2 documentation, I append ${_csrf.parameterName}=${_csrf.token} on the ajax URL. That doesn't help. I also try SS post method setting as the followings without any luck either.
var token = $("meta[name='_csrf']").attr("value");
var header = $("meta[name='_csrf_header']").attr("value");
//...
$(document).ready(function() {
new AjaxUpload('#uploadButton', {
action: "/shop/admin/products/images/upload",
name: 'uploadData',
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept","application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader(header, token);
},
onSubmit: function(file , ext) {
this.disable();
if (! (ext && /^(jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)$/.test(ext))){
alert('Error: invalid file extension');
return false; // cancel upload
}else {
// change button text, when user selects file
button.text(msg);
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 13){
button.text(text + '.');
} else {
button.text(msg);
}
}, 200);
}
},
onComplete: function(file, response) {
button.text(msg);
window.clearInterval(interval);
this.enable();
}
});
});
And a html related code:
<button id="uploadButton" type="button" class="btn btn-default" th:text="#{label.upload}"></button>
The other option mentioned in the SS documentation is a filter configuration order. The Java configuration of the application doesn't come with any filter configuration. So this option can't be applied.
How to deal with this problem?
According to the latest Spring Security documentation, the code should be $("meta[name='_csrf']").attr("content") instead of $("meta[name='_csrf']").attr("value") which seems to make sense because the HTML meta tag has a content attribute instead of a value attribute.
Could you make this change and try again?
A normal form, but note the hidden CSRF:
<form id="myForm" action="upload" method="post">
<input type="file" name="file">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
<input type="submit" value="Upload file!">
</form>
Ajaxify with jQuery Form Plugin:
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert("File was uploaded!");
});
});
Last step for success: Make sure you have MultipartFilter before Spring Security in your web.xml, as described in Spring Security reference, section CSRF Caveats.
jQuery Form Plugin has different strategies for file upload depending on browser, but the above should work regardless.

Displaying uploaded files from server in dropzone js

I am using the dropzone js plugin to upload files to a php server. It is working great. I am facilitating the user to update the uploaded files. So once the user clicks on update button, the dropzone appears, and I am able to display the uploaded files in it through a JQuery-AJAX call. But my problem is that though the files are displayed in the thumbnail format, the number of files in the dropzone counts to zero. I feel that the accept function is not being triggered.But if a new file is added to the displaying list the file count is 1 though there are files already existing in it.
I am using the following code to display the files in dropzone:
var mockFile = { name: "Filename", size: 12345 };
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, "/image/url");
Can anyone help me solve this?
I think you need to push the mockFile in the dropZone manually like this
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("complete", mockFile);
myDropzone.files.push(mockFile);
It's work for me... if you need more code just ask!
Mock file is not uploaded as explained here https://github.com/enyo/dropzone/issues/418
If you want to submit the form use myDropzone.uploadFiles([]); in init()
$('input[type="submit"]').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var form = $(this).closest('#dropzone-form');
if (form.valid() == true) { //trigger ASP.NET MVC validation
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([]);
}
}
});
example for U!
jQuery(function($) {
//文件上传
$(".dropzone").dropzone({
url : "pic_upload.jsp?id=<%=request.getParameter("id")%>",
addRemoveLinks : true,
dictRemoveLinks : "x",
dictCancelUpload : "x",
maxFiles : 5,
maxFilesize : 5,
acceptedFiles: "image/*",
init : function() {
//上传成功处理函数
this.on("success", function(file) {
alert("修改前:"+file.name);
});
this.on("removedfile", function(file) {
alert("File " + file.name + "removed");
//ajax删除数据库的文件信息
$.ajax({
type:'post',
url:'pic_delete.jsp?id='+file.name ,
cache:false,
success:function(data){
}
});
});
<%
if(null!=list){
for(PlaceImg img:list){%>
//add already store files on server
var mockFile = { name: "<%=img.getId()%>", size: <%=img.getFilesize()%> };
// Call the default addedfile event handler
this.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
this.emit("thumbnail", mockFile, "<%=img.getImgUrl()%>");
<%}
}%>
}
});

CodeIgniter - Multiple file uploads using dynamic field generation

Im using a jquery script to add new file upload fields to my form dynamically, as a result, all my file fields look like so
<input class="file-input-area" name="mpfile[]" type="file" size="32" value="" />
So in other words, if i click the 'add more file upload' link 5 times, i get 5 file upload fields that look exactly as the one above.
Iam quite new to codeigniter and have done some research which tells me that if uploading multiple files, i should use the [] after the field name ... i hope this is right.
My problem now is figuring the process to upload the files, and store their names to a database table.
I have tried normal PHP uploading but it doesnt seem to be working, im not sure what to put in my view, controller and model.
If someone can give me an example of how they would go about it, it would help me so much.
Cheers,
Use jQuery uploadify. The files are uploaded asynchronously, see some demos here.
Here's an implementation:
jQuery('#images').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/uploadify/uploadify.php',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/data/images',
'auto' : true,
'fileExt' : '*.jpg;*.gif;*.png;*.jpeg;*.tif',
'fileDesc' : 'Web Image Files (.JPG, .GIF, .PNG, .JPEG, .TIF)',
'queueID' : 'images-queue',
'onCancel' : function(event,ID,fileObj,data) {
jQuery.ajax({
type: "POST",
url: "uploadify/delete_image.php",
data: "filepath=/data/images/" + jQuery("#"+ID).val(),
success: function(){
jQuery("#"+ID).remove();
queueSize = data.fileCount;
jQuery('#status-message').text('Photo uploaded!');
}
});
},
'onSelect' :function (event, ID) {
if (queueSize < maxQueueSize)
queueSize++;
else{
alert("Max number of files is " + maxQueueSize);
jQuery('#images').uploadifyCancel(ID);
return false;
}
},
'onSelectOnce' : function(event,data) {
jQuery('#status-message').text('File is currently uploaded...');
},
'onComplete': function (evt, queueID, fileObj, response, data) {
jQuery('#status-message').text('H φωτογραφία φορτώθηκε!');
jQuery("#field_photos").append("<input id="+ queueID +" type='hidden' name='pics[]' value='" + response + "' />"); //adds hidden form field
},
'onAllComplete' : function(event,data) {
},
'onClearQueue' : function (a, b) {
queueSize = 0;
},
'multi' : true,
'simUploadLimit' : 3,
'removeCompleted': false,
'sizeLimit' : 1048576,
'queueSizeLimit' : 1
});
With this line:
jQuery("#field_photos").append("<input id="+ queueID +" type='hidden' name='pics[]' value='" + response + "' />"); //adds hidden form field
we store the filenames in the hidden array field "pics". When your form is submitted, you read these names using $this->input->post('pics') and store them into your database.

Resources