FineUploader button text - javascript

I have scoured the FineUploader documentation, but when I set my upload button text like below, the change does not seem to propagate. The upload button still displays the default text. What am I missing?
var manualuploader = new qq.FileUploader({
element: document.getElementById('manual-fine-uploader'),
text: {
uploadButton: "Select a File" // <========== Setting text here
},
action: "/file/upload",
autoUpload: false,
multiple: false,
forceMultipart: true,
onComplete: function (id, fileName, json) {
$("#divFileUploadLoading").hide();
$("#buttonUploadFile").show();
if (json.success) {
displaySuccessMessage("Successfully uploaded: " + fileName);
$("#textFileTitle").val("");
$("#textFileDescription").val("");
$("#checkIsDownloadable").prop("checked", true);
$("#checkDisplayDetails").prop("checked", true);
}
else {
displayErrorMessage("Failed to upload: " + fileName + " because '" + json.errorMessage + "'");
}
g_FileCount = 0;
manualuploader.clearStoredFiles();
manualuploader.reset();
},
onSubmit: function (id, fileName) {
g_FileCount++;
},
onCancel: function (id, fileName) {
$("#divFileUploadLoading").hide();
$("#buttonUploadFile").show();
displaySuccessMessage("Canceled upload for: " + fileName);
g_FileCount--;
}
});

Tested and verified. You still need to use the "text" option.
text: {
uploadButton:'<div>Select a file</div>'
}
Another way to do it is to create your own button with the button: option.
JS:
button: document.getElementById('my-button')
HTML:
<div id="my-button" class="qq-upload-button">Select a file</div>

As far as I'm concerned, the provided answers do not work. So what I did was to set the contents of the corresponding division programmatically after having called the FineUploader constructor. My Javascript is as follows (using jQuery):
$('div_ID').fineUploader({... your options here });
$(".qq-upload-button-selector.qq-upload-button div").text("your custom text");
I have tested this and it works for me. Any comments welcome.
Hope this helps.

try using an element:
uploadButton: "<div>Select a File</div>"
good luck !

Related

How can I send data to controller by dialog?

EDIT2: I'm trying to update my code with java, but it's not working (I suppose I miss something in controller):
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: {"graphicUrl": u, "graphicDesc": d},
success: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
$(this).dialog("close");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$("#graphicUrl").val("");
$("#graphicDesc").val("");
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
EDIT1:
Following Twisty suggestion I uptaded the dialog in order to not have any form inside (since this dialog is already in a form): https://jsfiddle.net/e57sj6hp/18/
As Twisty was also commenting, I probably need ajax, but I have to understand how use it; I think I need to use serialize() or seralizeArray(), but I don't understand well how should the controller receive the json and use it.
I have a controller like this:
public String myMethod(#ModelAttribute MyObject object, ModelMap model){...}
The object include a List of photos, and two variables url and description:
List<Photo> photos;
String url;
String description;
each photo in the list is formed by an url and a description.
In my jsp I created a dialog with jquery where a user can put an url and a description, what I want to do is to add each value into a list and send it to the controller, then clean the dialog in order to allow another submission.
I have tried a lot of but can't understand how I should do it. I'm using the spring's form and I have tried many different ways, but I think that the problem is in my javascript code. Here's one example: https://jsfiddle.net/e57sj6hp/12/
In this example the input fields and the textarea inside the dialog aren't surrounded with spring's form tags, since I've append the result inside the div and I supposed that, at the moment of the submitting, the controller should receive the data inside the form:input just created.
Not familiar with Spring, so I may miss an element, but matching what you put in your example, I can offer some potential updates.
Working Example: https://jsfiddle.net/Twisty/e57sj6hp/16/
HTML Updated
<div id="insertPhoto" style="display:none" title="Insert a Photo">
<form id="newPhoto">
<label>Url:</label>
<br/>
<input id="graphicUrl" />
<br/> Description:
<br/>
<textarea rows="4" cols="20" id="graphicDesc"></textarea>
</form>
</div>
You cannot call form.reset() without a form element. I wrapped the the form elements in a form. This has the added benefit of now responding to the form being submitted, for example if the user enters a url and hits enter.
jQuery
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc);
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$(this)[0].reset();
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
Lots of little fixes and improvements here. I moved listGraphic out of the functions, so it can be updated more globally. This allows it to be updated and read from other callbacks.
I created the function to make it a little easier to repeat.
Now regardless of how the form is submitted, the array is updated and so is the page. The dialog is closed and it's form is reset.
UPDATE 1
See new jQuery: https://jsfiddle.net/Twisty/e57sj6hp/21/
jQuery
$(document).ready(function() {
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: JSON.stringify({
"graphicUrl": u,
"graphicDesc": d
}),
complete: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
addPhoto($("#graphicUrl").val(), $("#graphicDesc").val());
// Reset values
$("#graphicUrl").val("");
$("#graphicDesc").val("");
// Close Dialog
$(this).dialog("close");
}
}
});
});

Krajee Bootstrap fileinput how can i change the uploadExtraData dynamically

Hi Am using Krajee Bootstrap fileinput , i need to change the uploadExtraData dynamically on submitting the form. So i made it as a call back function. But it doesn't work for me. As i think uploadExtraData callback function work at on initialization only.
here is my code
$(".file-loading").fileinput({
uploadUrl: document.location.origin + "/discussions/add",
uploadAsync: false,
uploadExtraData:getFormData(),
});
function getFormData(){
var project_id = $("#DiscussionProjectId").val();
var discussion_title = $("#DiscussionDiscussionTitle").val();
var comment = $('#discussionComment').attr('value');
var data = {
project_id:project_id,
discussion_title:discussion_title,
comment:comment
};
return data;
}
Am doing to save the input files and data on form submit only.
I met the same problem with you,you can try this:
$(".file-loading").fileinput({
uploadUrl: document.location.origin + "/discussions/add",
uploadAsync: false,
uploadExtraData:function(previewId, index) {
var data = {
project_id : $("#DiscussionProjectId").val(),
discussion_title:$("#DiscussionDiscussionTitle").val(),
comment:$('#discussionComment').attr('value')
};
return data;
},
});
Its also possible to destroy the control and recreate it again
self.jqueryObjects.fileInput.fileinput('destroy');
self.jqueryObjects.fileInput.fileinput({
showCaption: false,
uploadUrl: self.urls.uploadDocument.replace(/<patient_id>/g, self.selectedPatient.id),
allowedFileExtensions: ["txt"]
});

jQuery File Upload in Rails 4.x Nested Form

I have a Horse model and a Photo model. I am using jQuery File Upload to resize (client side) images and save on Amazon s3 directly since I am using Heroku.
I have seen other questions similar that use carrierwave, paperclip, or that are very old. I am not sure why you would use carrierwave/paperclip, but I think based on what heroku says, I do not want to have images hitting the server potentially causing time-outs.
Heroku recommends using jQuery File Upload and shows js appending new file input with a value of the image's link (returned from amazon s3). I have this working when saving a photo separately. I now want to make it work in a nested form for Horse but js is not finding input (since it does not exist yet because it's nested I presume).
I am using Cocoon for nested forms (I am open to anything that will work better). I am not too familiar with javascript/jQuery but a far as I can tell, Cocoon 'hides' the nested element until I click to add it via the add_association.
haml view code:
= link_to_add_association 'add photo', f, :photos
html source before clicking 'add photo'
<div class='links'>
<a class="btn btn-default btn-sm add_fields" data-association-insertion-method="after" data-association="photo" data-associations="photos" data-association-insertion-template="<div class='nested-fields'>
<fieldset class="inputs"><ol><input type="file" name="horse[photos_attributes][new_photos][url]" id="horse_photos_attributes_new_photos_url" />
<input type="hidden" name="horse[photos_attributes][new_photos][_destroy]" id="horse_photos_attributes_new_photos__destroy" value="false" /><a class="remove_fields dynamic" href="#">remove photo</a>
</ol></fieldset>
</div>
" href="#">add photo</a>
How do I work with this input and how do I handle multiple file uploads as they are added correctly?
My current upload js:
$(function() {
if ($('#new_horse').length > 0) {
$.get( "/presign", function( s3params ) {
$('.direct-upload').find("input:file").each(function(i, elem) {
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.fileupload({
fileInput: fileInput,
url: "http://" + s3params.url.host,
type: 'POST',
autoUpload: true,
formData: s3params.fields,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
disableImageResize: false,
imageQuality: 0.5,
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 500,
imageMaxHeight: 1000,
imageOrientation: true, //auto rotates images
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //I added this to jquery.fileupload-validate: alert('Must Be JPG GIF or PNG Image')
replaceFileInput: false,
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true);
fileInput.after(barContainer);
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Pre-uploading done... Please Save or Cancel");
// extract key and generate URL from response
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = 'https://' + s3params.url.host +'/' + key;
// remove first input to prevent phantom upload delay
fileInput.remove();
// create new hidden input with image url
var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
var imgPreview = '<img src="' + url + '">';
form.append(input);
form.append(imgPreview);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed");
}
});
});
}, 'json');
}
});
I guess I should have looked at cocoon documentation first:
http://www.rubydoc.info/gems/cocoon#Callbacks__upon_insert_and_remove_of_items_
http://www.rubydoc.info/gems/cocoon/1.2.6
I modified my upload.js file to the following and it worked for multiple files in nested forms perfectly:
// added for file uploading
// https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails
// Get our s3params from our endpoint
$(document).on('ready page:load', function () {
$('.direct-upload')
.on('cocoon:after-insert', function(e, photo) {
console.log('inside cocoon image function');
$.get( "/presign", function( s3params ) {
$('.direct-upload').find("input:file").each(function(i, elem) {
console.log('inside nested-fields photo input form');
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.fileupload({
fileInput: fileInput,
url: "http://" + s3params.url.host,
type: 'POST',
autoUpload: true,
formData: s3params.fields,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
disableImageResize: false,
imageQuality: 0.5,
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 500,
imageMaxHeight: 1000,
imageOrientation: true, //auto rotates images
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //I added this to jquery.fileupload-validate: alert('Must Be JPG GIF or PNG Image')
replaceFileInput: false,
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true,
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true);
fileInput.after(barContainer);
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Photo Uploaded");
// extract key and generate URL from response
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = 'https://' + s3params.url.host +'/' + key;
// remove first input to prevent phantom upload delay
fileInput.remove();
// create new hidden input with image url
var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
var imgPreview = '<img src="' + url + '">';
form.append(input);
form.append(imgPreview);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed");
}
}, 'json'); //fileupload
}); //each file
}); //presign call
}); // function cocoon
}); // page ready
I guess Google and a well documented gem can replace knowledge of JS in the short term :-) I am sure it's not at tight as it could be so please offer any improvements.

How can i check number of files selected with Fine Uploader?

I am using manual uploading via Fine Uploader. Now i want to check that file has selected or not.
$(document).ready(function() {
var fineuploader = new qq.FineUploader({
element: $('#fine-uploader')[0],
request: {
endpoint: '<?php echo site_url('pl_items/upload_images');?>'
},
multiple: true,
autoUpload: false,
onLeave: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 5120000 // 50 kB = 50 * 1024 bytes
},
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
template: '<div class="qq-uploader">' +
'<pre class="qq-upload-drop-area"><span>{dragZoneText}</span></pre>' +
'<div class="qq-upload-button btn btn-danger">{uploadButtonText}</div>' +
'<div class="qq-drop-processing span1"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></div>' +
'<div><ul class="qq-upload-list"></ul></div>' +
'</div>',
callbacks: {
onComplete: function(id, name, response) {
$('#frmDetails').append('<input type="hidden" name="pl_item_images[]" value="'+response.file_name+'">');
//$("#frmDetails").submit();
}
},
});
$('#submit_button').click(function() {
fineuploader.uploadStoredFiles();
});
});
Since you haven't responded to my question, I'll just assume that you want to determine if a file has been selected before you call uploadStoredFiles in your click handler.
It's really very simple. Just make use of the getUploads API method. For example, you could change your click handler to look like this:
$('#submit_button').click(function() {
var submittedFileCount = fineuploader.getUploads({status: qq.status.SUBMITTED}).length;
if (submittedFileCouunt > 0) {
fineuploader.uploadStoredFiles();
}
});
A few more things:
There is no onLeave option. You should remove this from your code.
The multiple option defaults to true. You can remove this from your code as well.
You are already using jQuery. Why aren't you using the Fine Uploader jQuery plug-in? See the documentation for instructions.

How to append files to formData

I am obtaining files and their values in a non-normal way. There isn't an actual input in the form. Therefore, I am trying to append the files to the formData for ajax submission.
Anytime I try to submit the form with the method below, my files aren't uploading. Therefore, the way I am appending the files must be incorrect.
I was told the following from someone, but I can't figure out how to do it:
You're looping through the array but appending the entire array every
time through the loop. Use the brackets on the form input name and
append each file in the array.
Does anyone see what I need to change to get this to work?
Code for the dropzone...before the relevant code below:
var dragFileName = '';
var myDropzone = new Dropzone("#myDropzone", {
//$('#myDropzone').dropzone ({
//Dropzone.options.myDropzone= {
url: 'php/quoteSendTest.php',
autoProcessQueue: false,
paramName: "file",
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 25,
acceptedFiles: 'image/*',
addRemoveLinks: true,
dictFileTooBig: 'File is larger than 25MB',
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
/* document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
console.log("Something should be showing for eventListener");
//e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});*/
this.on("addedfile", function(file) {
/* Maybe display some more file information on your page */
dragFileName = file.name;
var dragFileSize = file.size;
var count = myDropzone.files.length;
console.log('File added - ' + file.name + ' - Size - ' + file.size);
console.log(count + " is the length");
//console.log("FILEname is " + dragFileName);
setTimeout(function () {
toggleUploadButton();
}, 10);
});
//send all the form data along with the files:
/*this.on("sendingmultiple", function(data, xhr, formData) {
//formData.append("firstname", jQuery("#firstname").val());
//formData.append("lastname", jQuery("#lastname").val());
});
*/
}
});
Relevant code:
var acceptedFiles = null;
var allAcceptFiles = null;
function toggleUploadButton() {
acceptedFiles = myDropzone.getAcceptedFiles();
allAcceptFiles = acceptedFiles.values();
for (let fileElements of allAcceptFiles) {
console.log(fileElements);
}
}
function submit(){
var form = document.getElementById("salesforce_submit");
var formData = new FormData(form);
fileElements.each(function() {
formData.append('uploadedFile[]', fileElements);
});
alert(formData);
$.ajax({
url: '/php/quoteSendTest.php',
type: 'POST',
data: formData,
HTML:
<form action="<?php echo $config['sf_url']; ?>" method="POST" id="salesforce_submit">
<input id="first_name" name="first_name" type="text">
<div class="dropzone dz-clickable" id="myDropzone">
<div class="dz-default dz-message dG">Drop files here or click to upload</div>
</div>
<button type="submit" id="submit-all">SEND PROJECT QUOTE</button>
</form>
Console.log info from fileElements:
File {upload: {…}, status: "queued", previewElement:
div.dz-preview.dz-file-preview, previewTemplate:
div.dz-preview.dz-file-preview, _removeLink: a.dz-remove, …} accepted:
true dataURL: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABtUA"
height: 892 lastModified: 1512405192880 lastModifiedDate: Mon Dec 04
2017 11:33:12 GMT-0500 (Eastern Standard Time) {} name:
"analytics.PNG" previewElement: div.dz-preview.dz-image-preview
previewTemplate: div.dz-preview.dz-image-preview size: 544438 status:
"queued" type: "image/png" upload: {uuid:
"6dc946e7-e9db-4b3a-88af-b790de1c2975", progress: 0, total: 544438,
bytesSent: 0, filename: "analytics.PNG", …} webkitRelativePath: ""
width: 1749
_removeLink: a.dz-remove
proto: File
In your initial attempt:
function toggleUploadButton() {
acceptedFiles = myDropzone.getAcceptedFiles();
allAcceptFiles = acceptedFiles.values();
for (let fileElements of allAcceptFiles) {
console.log(fileElements);
}
}
var formData = new FormData(form);
fileElements.each(function() {
formData.append('uploadedFile[]', fileElements);
});
You are looping through allAcceptFiles and setting each one to fileElements. This leaves fileElements as a single file, and when try to do the each loop later it doesn't act as you'd expect.
I noticed that myDropzone must be defined somewhere, since it was working in the first function. Looking at the dropzone documentation, I saw it had a getAcceptedFiles method that you could easily use to loop through and add each file to the form data. The modified loop is below:
var formData = new FormData(form);
myDropzone.getAcceptedFiles().forEach(file => {
formData.append("uploadedFile[]", file);
});
There are a couple other things that don't seem necessary in the code, but this isn't code review so I'll leave them alone.

Categories

Resources