Delegate uploadfile event to control dynamically loaded - javascript

I am using a fileupload event assigned to #fileupload control. When I put this code in a static page it works well, but I want this control to load in a Javascript template like this:
<script type="text/template" id="propertyCollectionTemplate">
<span id="firstUpload" class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
</script>
this template is loaded when clicking in one table row in my stage
$('table.collection tbody tr').click(function (e) {
e.preventDefault();
var m = page.properties.get(this.id);
page.showDetailDialog(m);
});
In my showDetailDialog function have this code:
showDetailDialog: function (m) {
// show the modal dialog
$('#propertyDetailDialog').modal({ show: true });
// ... fecth all data for my other controls....
This is my upload event bound in static mode:
$('#fileupload').fileupload({
url: page.url,
dataType: 'json',
done: function (e, data) {
alert("hola");
$.each(data.result.files, function (index, file) {
$('#propertyimage').val("/propertylocator/upload/server/php/files/" + file.name);
});
$('#progress .progress-bar').css('width', 0 + '%');
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css('width', progress + '%');
}
}).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
If I copy and paste this event in Chrome console when modal popup is loaded this work well, but I don't know how to delegate this event once I have loaded the template.

There are two ways:
First way:
Initiate fileupload initially (before inserting template) and set the properties on change:
$('#fileupload .files').on('change', ':file', function (e) {
$('#fileupload').fileupload('add', {
fileInput: $(this)
});
});
More details here: https://github.com/blueimp/jQuery-File-Upload/issues/1260
Second way:
Bind fileupload after inserting template in a callback, like:
$('table.collection tbody tr').click(function (e) {
// your 'click' code
e.preventDefault();
var m = page.properties.get(this.id);
page.showDetailDialog(m);
// bind fileupload
$('#fileupload').fileupload({
// ...
});
});
More details here: jQuery File Upload not working when file input dynamically created

Related

JqueryFileUpload form url issue

I try to use JQueryFileUpload plugin to make ajax upload while form filling. But I have hard issue because I need to have different url to those in form params.
I use url param in JQueryFileUpload object but it doesnt works well if file input field is located in form. Then it uses form action url 'index.php?option=com_xxx&layout=edit&id=0' in .fileupload function instead of this url 'index.php?option=com_xxx&task=item.uploadImage'.
How to use ulr param in fileupload function and have file field inside some form with different action url? Is it possible?
JQuery code:
jQuery('#jform_file').fileupload({
url: 'index.php?option=com_xxx&task=item.uploadImage',
// This element will accept file drag/drop uploading
dropZone: jQuery('#drop'),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
var tpl = jQuery('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
previewImage(data);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
}
});
Form html:
<form action="index.php?option=com_xxx&layout=edit&id=0" method="post" name="adminForm" id="adminForm" class="form-validate">
<input type="file" name="jform[file]" id="jform_file" />
</form>
By accident I found out the solution. I added one more fileupload call before the right one:
jQuery(function(){
jQuery('#adminForm').fileupload();
jQuery('#jform_file').fileupload({
url: 'index.php?option=com_xxx&task=item.uploadImage',
});
});
First one return form action url result so it can cause some issues. But second call returns result from url param.

jQuery File Upload hooked to button

I am attempting to use the jQuery File Upload Plugin here
The behavior I want is similar to the home page that loads - i.e - the ability to select multiple files - when selected I don't need the button to upload files individually (just remove with the cancel button individually) and remove all with the cancel button along the top bar
I am developing my site in c# mvc and the file gets uploaded to a ECM solution via CMIS Browser Bindings so I dont actually hit an MVC controller method. As I am using Browser Bindings I need to upload each file individually to the CMIS Endpoint. The code works fine doing an auto data submit for each file
So the working code I have is:
$('#uploadFile').fileupload({
replaceFileInput: false,
singleFileUploads: true,
add: function (e, data) {
$.each(data.files, function (index, file) {
data.url = 'mycmis_url';
data.type = 'POST';
data.submit();
});
},
done: function (e, data) {
alert("Done");
}
});
If I do have 3 files selected to upload I will get 3 'Done' alerts but the 3 files all upload successfully. However as mentioned the behavior I want is one Uppload All button that would trigger the upload for each of my selected files. I have the code below:
$('#uploadFile').fileupload({
replaceFileInput: false,
singleFileUploads: true,
autoUpload: false,
add: function (e, data) {
$.each(data.files, function (index, file) {
data.url = 'mycmis_url';
data.type = 'POST';
});
$("#uploadAllFilesBtn").unbind('click').on('click', function () { data.submit(); });
},
done: function (e, data) {
alert("Done");
}
});
So I have set the autoUpload property to false but if I select two files and then click my Upload All Files button as my uploadAllFiles button is outside my each loop if my first selected file is called foo.txt and my 2nd selected file is bar.txt it will only upload bar.txt.
Has anyone got any idea how I could have a button called upload all that would trigger a data.submit for each individual file?
Incorporating code from your later question:
$('#uploadFile').fileupload({
replaceFileInput: false,
singleFileUploads: true,
add: function(event, data) {
data.url = 'myUrl';
data.type = 'POST';
data.context = $('<tr>'
+ '<td><strong>Selected File : </strong>' + data.files[0].name + '</td>'
+ '<td> </td>'
+ '<td><button type="button" class="removeBtn btn btn-default">'
+ '<span class="glyphicon glyphicon-remove-circle"></span>'
+ 'Remove File</button></td>'
+ '</tr>')
.appendTo('#files')
.data('data', data);
}
});
$('#files').on('click', '.removeBtn', function() {
$(this).closest('tr').remove();
});
$('#uploadAllFiles').click(function() {
var jqXHRs = [];
$('#files').find('tr').each(function() {
jqXHRs.push($(this).data('data').submit());
});
$.when.apply($, jqXHRs).done(function() {
alert('done');
});
});
Note:
Since you have singleFileUploads set to true, the data.files array will always contain exactly one file.
The data is attached to the <tr> element using jQuery's .data() function.
For the "Remove" buttons, the code is using event delegation, which was suggested by #Ekansh's answer to your other question.

Dynamically use bleuimp jquery file upload

I am using the blueimp JQuery fileupload, however I would like to use it dynamically. I've got about 5 elements on my webpage and each of them should call the javascript function (auto upload) when a file was selected. Below is the basic version of bleuimp JQuery file upload. Instead of using a div called #fileupload, I have 5 divs with ids #fileupload1 to #fileupload5.
I would like to get the javascript code working for all 5 #fileupload id's using a single javascript block. So basically I am looking to use the code below but for all 5 elements. Is there a way to do that and if so does someone have an example for me? Thanks for any help.
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
alert('DONE');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I found a solution. Maybe not the best one but so far it works for me.
$('.dp-upload-container').each(function () {
// Code from $(function() { }); here using different ID's and classes dynamically.
});

Cancel file in file selection box with jquery button click

With jquery button click i need to cancel(drop, discard) file that i choose to upload
Here is my jquery code:
$('.upic9').bind('click', { imgId: $(this).attr('id') }, function (evt) {
$('.fileselectionbox').empty();
});
you can use jQuery File Upload plugin
I guess this can works in your case.
jQuery File Upload plugin
probably this code example will help you.
I'm not sure if html5 works for your case, if not see link above
$('#html5FileInput').fileupload({
....
add: function (e, data) {
$.each(data.files, function (index, file) {
var newFileDiv = $(newfileDiv(file.name));
$('#fsUploadProgressHtml5').append(newFileDiv);
newFileDiv.find('a').bind('click', function (event) {
event.preventDefault();
var uploadFilesBox = $("#fsUploadProgressHtml5");
var remDiv = $(document.getElementById("fileDiv_" + event.data.filename));
removeFileFromArray(event.data.filename);
remDiv.remove();
data.files.length = 0;
...
});
data.context = newFileDiv;
});
...
)};
or see this

jQuery File Upload - how to recognise when all files have uploaded

I'm using the jQuery File Upload plugin.
I would like to be able to trigger an event when all selected files have finished uploading. So far I have an event for doing an action when a file(s) is selected for uploading and when each particular file finishes uploading - is there a way to detect that all selected files have finished uploading?
The actual app is here http://repinzle-demo.herokuapp.com/upload
My input field looks like this:
<div id="fine-uploader-basic" class="btn btn-success" style="position: relative; overflow: hidden; direction: ltr;">
My script code looks like this:
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
add: function (e, data) { // when files are selected this lists the files to be uploaded
$.each(data.files, function (index, file) {
$('<p/>').text("Uploading ... "+file.name).appendTo("#fileList");
});
data.submit();
},
done: function (e, data) { // when a file gets uploaded this lists the name
$.each(data.files, function (index, file) {
$('<p/>').text("Upload complete ..."+file.name).appendTo("#fileList");
});
}
});
});
</script>
I am handling the request with a Play Framework (Java) controller that looks like this:
publi
c static void doUpload(File[] files) throws IOException{
List<ImageToUpload> imagesdata = new ArrayList<ImageToUpload>();
//ImageToUpload has information about images that are going to be uploaded, name size etc.
for(int i=0;i<files.length;i++){
Upload upload = new Upload(files[i]);
upload.doit(); //uploads pictures to Amazon S3
Picture pic = new Picture(files[i].getName());
pic.save(); // saves metadata to a MongoDB instance
imagesdata.add(new ImageToUpload(files[i].getName()));
}
renderJSON(imagesdata);
}
I think you are looking for 'stop' event:
$('#fileupload').bind('fileuploadstop', function (e) {/* ... */})
as said in the plugin documentation:
Callback for uploads stop, equivalent to the global ajaxStop event
(but for file upload requests only).
You can also specify the function on plugin creation passing it as parameter
$('#fileupload').fileupload({
stop: function (e) {}, // .bind('fileuploadstop', func);
});
Here's the solution you want:
$('#fileupload').on('fileuploaddone', function(e, data) {
var activeUploads = $('#fileupload').fileupload('active');
if (activeUploads == 1) {
console.info("All uploads done");
}
});
I was with this problem also, fixed 3 years ago.

Categories