Fineuploader cancel upload after user response on file submit - javascript

I am trying to get user response on file submit to cancel or not to cancel file upload but it doesn't seem to stop file upload may be I am missing something pls suggest
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, old one will be replaced") == false){
manualuploader.cancelAll(); // tried but does not work
cancelAll();// tried but does not work
cancel(id);// tried but does not work
$(this).cancelAll();// tried but does not work
}
}
},
And yes I am able to successfully upload files ......
And this is complete function I am using ...
var manualuploader = new qq.FineUploader({
callbacks : {
onComplete : function(id, name, response) {
}
},
element : $('#pdf-fine-uploader')[0],
request : {
endpoint : "/UploadPdf",
params : {
variant_id : $('#variant_id').val(),
}
},
multiple : false,
autoUpload : true,
text : {
uploadButton : '<i class="icon-plus icon-white"></i> Select File </br> Maximum upload size less than 2 MB'
},
validation : {
allowedExtensions : ['pdf', 'txt'],
//sizeLimit: 51200, // 50 kB = 50 * 1024 bytes
sizeLimit : 2097152//, // 2 MB = 2 * 1024 * 1024 bytes
//itemLimit : 6
},
callbacks : {
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
// var answer = confirm("Please note, if you upload a new PDF, your current Tasting Notes PDF will be replaced");
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, your current Tasting Notes PDF will be replaced") == false){
manualuploader.cancelAll();
}
}
},
onComplete : function(id, fileName, responseJSON) {
if (responseJSON.success) {
$('.doc_link').html(responseJSON.docurl);
$('#doc_delete_link').addClass('icon-remove-sign');
$('.doc_description_head').show();
$('#doc_pdf_head').show();
$('.doc_description_div').show();
$('.description_save').show();
$('#doc_delete_link').show();
}
}
}
});
$('#triggerUpload').click(function() {
manualuploader.uploadStoredFiles();
});
});

Finally got very simple solution ...
just use
retrun true or false after getting user response ....
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, old one will be replaced") == false){
retutn false;
}
}
},

Related

JavaScript: Dropzone.js - Adding File Size and Dimensions to Form Submission

I'm testing some example code for Dropzone.js and would like to see if I could get the file size to submit as a form field:
var KTFormsDropzoneJSDemos = {
init: function(e) {
new Dropzone("#kt_dropzonejs_example_1", {
url: "add/submit/",
paramName: "file",
maxFiles: 10,
maxFilesize: 10,
addRemoveLinks: !0
}),
function() {
const e = "#kt_dropzonejs_example_3",
o = document.querySelector(e);
var r = o.querySelector(".dropzone-item");
r.id = "";
var t = r.parentNode.innerHTML;
r.parentNode.removeChild(r);
var l = new Dropzone(e, {
url: "add/submit/",
parallelUploads: 20,
maxFilesize: 0.25, // 1 MB
acceptedFiles: ".jpeg,.jpg",
previewTemplate: t,
previewsContainer: e + " .dropzone-items",
clickable: e + " .dropzone-select"
});
l.on("addedfile", (function(e) {
o.querySelectorAll(".dropzone-item").forEach((e => {
e.style.display = ""
}))
})), l.on("totaluploadprogress", (function(e) {
o.querySelectorAll(".progress-bar").forEach((o => {
o.style.width = e + "%"
}))
})), l.on("sending", (function(e) {
o.querySelectorAll(".progress-bar").forEach((e => {
e.style.opacity = "1"
}))
})), l.on("complete", (function(e) {
const r = o.querySelectorAll(".dz-complete");
setTimeout((function() {
r.forEach((e => {
e.querySelector(".progress-bar").style.opacity = "0", e.querySelector(".progress").style.opacity = "0"
}))
}), 300)
}))
}()
}
};
KTUtil.onDOMContentLoaded((function() {
KTFormsDropzoneJSDemos.init()
}));
The Dropzone.js "Tips & Tricks" page lists an example of how to send the file size, height, and width:
Dropzone adds data to the file object you can use when events fire. You can access file.width and file.height if it’s an image,
If you want to add additional data to the file upload that has to be specific for each file, you can register for the sending event:
myDropzone.on("sending", function(file, xhr, formData) {
// Will send the filesize along with the file as POST data.
formData.append("filesize", file.size);
});
I have the "sending" section in the example code under the #kt_dropzonejs_example_3 section, but I cannot figure out how to append the data like they have using the example code. How can I edit the "sending" code to add the file size as form data?
Per the example, you should accept the other parameters when you handle the sending event:
l.on("sending", (function(file, xhr, formData) {
o.querySelectorAll(".progress-bar").forEach((e => {
e.style.opacity = "1"
}));
formData.append("filesize", file.size);
})),
Per my comment about formatting, my personal preference would be for the code to look something like this:
dropzoneExample3.on("sending", (file, xhr, formData) => {
dropzoneElement.querySelectorAll(".progress-bar").forEach(element => element.style.opacity = "1");
formData.append("filesize", file.size);
});

Reset FilePond Input in Javascript

I have implemented Filepond uploaded in my page. When the user selects a file, I set that file on a html canvas for edits. However when the user wants to upload another file, filepond input retains last uploaded file.
I have tried FilePond.destroy(inputElement); after the file is successfully set on the canvas in the FilePond:addfile event.
$('.upload-file').filepond();
$.fn.filepond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize,
FilePondPluginImageResize,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageValidateSize,
);
FilePond.setOptions({
labelIdle: 'Drag & Drop your file or <span class="filepond--label-
action"> Browse </span>',
maxFiles: 1,
allowDrop: true,
allowMultiple: false,
dropOnPage: true, //for page to work, element has to be false https://github.com/pqina/filepond/issues/113
dropOnElement: false,
labelTapToCancel: '', //we dont want to allow cancel
labelTapToUndo: '',
maxFileSize: intFileSizeInMB,
allowReplace: true,
allowRevert: false,
instantUpload: false
});
const pond = document.querySelector('.filepond--root');
pond.addEventListener('FilePond:addfile', e => {
console.log('File added', e.detail);
if (e.detail) {
if (e.detail.file && e.detail.file.file.name) {
SetFileOnCanvas(e.detail.file.file, e.detail.file.file.name);
const inputElement = document.querySelector('input[type="file"]');
FilePond.destroy(inputElement);
}
}
});
pond.addEventListener('FilePond:processfile', e => {
console.log('Process File COMPLETE', e.detail);
});
After a file is uploaded and set to Canvas the file upload input should be cleared and ready for another upload.
Working solution
var pond_ids = [];
if (pond.getFiles().length != 0) { // "pond" is an object, created by FilePond.create
pond.getFiles().forEach(function(file) {
pond_ids.push(file.id);
});
}
pond.removeFiles(pond_ids);
After upload file "Complete function"
you can do like this (simple example):
if (filePond.getFiles().length != 0) {
for (var i = 0; i <= filePond.getFiles().length - 1; i++) {
filePond.removeFile(filePond.getFiles()[0].id)
}
}
I know its too late but you can use
let filePond = FilePond.find(document.getElementById(filePondElementId));
if (filePond != null) {
//this will remove all files
filePond.removeFiles();
}
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
Assuming that you create your filepond instance through function create_pondProfile and your input has class filepond, in you filepond config in server block do like this:
server: {
url: '',
process: {
url: '/path/to/upload/',
headers: {'X-CSRF-TOKEN': csrf},
ondata: (formData) => {
return formData;
},
onload: (response) => {
FilePond.destroy(document.querySelector('.filepond'));
create_pondProfile('.filepond');
}
},
...
...
}
It will destroy current instance of filepond and creates new one after upload.

How to do override uploadifive method?

Please give me code example for override any method of uploadifive.
Here i have putted my js code, please have your look. i want to check duplicate file from backend. I have already method in controller.
If you give any sample for how i can override method then i can try ahead.
$('#file_upload').uploadifive({
'auto' : true,
'buttonText' : 'Select File',
'checkScript' : false,
'queueSizeLimit' : 10,
'fileSizeLimit' : 10737418240,
'dnd' : false,
'multi' : true,
'removeCompleted' : true,
'queueID' : 'queue',
'simUploadLimit' : 30,
'uploadLimit' : 30,
'overrideEvents' : ['onProgress'],
'uploadScript' : '/files/pending',
// Triggered for each file that is added to the queue
'onAddQueueItem' : function(file) {
console.log(file.name + "file that is added to the queue");
var folder = files.currentItemData();
this.data('uploadifive').settings.formData = {
'timestamp' : current_date_time(),
'authenticity_token' : token(),
'attachment[folder_id]' : folder.id,
'attachment[context_code]' : current_context_code(),
'attachment[language]' : uploadifive_language_code(),
'success_action_status' : "201",
//'attachment[duplicate_handling]': file.duplicate_handling,
};
},
// Triggered when a file is cancelled or removed from the queue
'onCancel' : function() {},
// Triggered when the server is checked for an existing file
'onCheck' : function() {},
// Triggered during the clearQueue function
'onClearQueue' : function() {},
// Triggered when files are dropped into the file queue
'onDrop' : function() {},
// Triggered when an error occurs
'onError' : function(file, fileType, data) {},
// Triggered if the HTML5 File API is not supported by the browser
'onFallback' : function() {},
// Triggered when UploadiFive if initialized
'onInit' : function() {},
// Triggered once when an upload queue is done
'onQueueComplete' : function(file, data) {},
// Triggered during each progress update of an upload
'onProgress' : function(file, e) {
if (e.lengthComputable) {
var percent = Math.round((e.loaded / e.total) * 100);
}
$('.uploadifive-queue-item').find('.fileinfo').html(' - ' + percent + '%');
$('.uploadifive-queue-item').find('.progress-bar').css('width', percent + '%');
},
// Triggered once when files are selected from a dialog box
'onSelect' : function(file) {
console.log(file.queued + ' files were added to the queue.');
return;
},
// Triggered when an upload queue is started
'onUpload' : function(file) {
console.log(file + ' files will be uploaded.');
file_select_done();
},
// Triggered when a file is successfully uploaded
'onUploadComplete' : function(file, data) {
res_data = JSON.parse(data);
$.ajaxJSON(res_data.success_url,'GET',{"authenticity_token" : authenticity_token},function(data) {
if (data && data["attachment"]){
var file_id = data["attachment"]["id"];
var file_name = data["attachment"]["display_name"];
generate_li(file_name, file_id);
qutaUpdate();
}
});
console.log('The file ' + file.name + ' uploaded successfully.');
},
// Triggered for each file being uploaded
'onUploadFile' : function(file) {
console.log('The file ' + file.name + ' is being uploaded.');
}
});});
I found answer of my above question: :)
$('#file_upload').uploadifive({
'overrideEvents' : ['onProgress','onCheck'],
});
I putted uploadifive method in array and now all my code calling here not uploadifive's code.
Thanks!

Cancel uploads in onStatusChange

In our system we only allow uploads up to a specific number which can be done in multiple upload sessions. When the number of images in an upload session exceed this maximum number we are currently cancelling uploads in onStatusChange() instead of adjusting itemLimit:
thumbnailuploader = new qq.FineUploader({
element: document.getElementById('thumbnail-fine-uploader'),
template: "qq-simple-thumbnails-template",
request: {
endpoint: 'uploader/uploader.php'
},
thumbnails: {
placeholders: {
waitingPath: "uploader/waiting-generic.png",
notAvailablePath: "uploader/not_available-generic.png"
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp'],
itemLimit: 6
},
callbacks: {
onSubmit: function(id, fileName){
// console.log("submitting..." + id);
},
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(parseInt(galleryImages) + id + 1 > MaxUploads && newStatus !== qq.status.CANCELLED){
this.cancel(id);
return;
}
if (newStatus === qq.status.CANCELLED) {
check_done();
return;
}
},
onComplete: check_done,
onUpload: StartUpload
}
});
This seems to work well, but when switching on the debugger I get:
Error: [Fine Uploader 5.0.3] 1 is not a valid file ID to upload!
in
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
and a bunch of:
"[Fine Uploader 5.0.3] Caught exception in 'onStatusChange' callback - element is undefined"
Can this be fixed or are these messages harmless?
Thanks!

getting an error - Caught error in Fine Uploader jQuery event handler: Object [object Object] has no method 'getUploads'

UPpated this question.
the issue I am having is trying to get the number of jobs submitted using the getUploads API.
when I call the function I am always getting 0 (zero).
Not sure what I did incorrect.
Matt
<script>
// Wait until the DOM is 'ready'
$(document).ready(function () {
var myUploader = $("#fine-uploader").fineUploader({
session: {
endpoint: 'imageStatus.cfm',
params : {transaction_id : <cfoutput>#client.transaction_id#</cfoutput>}
},
debug: true,
request: {
endpoint: 'upload.cfm',
params : {details : "<cfoutput>#client.wallfolder#|#client.DonatorID#|#client.wallid#|#client.transaction_id#|#client.clientid#</cfoutput>"}
},
validation: {
itemLimit: <cfoutput>#evaluate(client.numberofbricks*3)#</cfoutput>,
allowedExtensions: ["jpeg", "jpg", "gif" , "png"],
sizeLimit: 5000000 // 5 MiB
},
messages: {
tooManyItemsError: 'You can only add <cfoutput>#client.numberofbricks#</cfoutput> images'
},
deleteFile: {
enabled: true, // defaults to false
endpoint: 'upload_delete.cfm',
method: 'post',
params : {wallid : "<cfoutput>#client.wallid#</cfoutput>"}
},
retry: {
enableAuto: false
},
scaling: {
sendOriginal: true,
hideScaled: true,
sizes: [
{name: "THUMB_XX", maxSize: 113},
{name: "FULLIMAGE", maxSize: 450}
]
}
})
.on('allComplete', function(responseJSON) {
if (qq.status.UPLOAD_SUCCESSFUL == 'upload successful') {
//get uuid for message
if ($(this).fineUploader("getNetUploads") > 0){
$("#ContinueButton").show();
}else{
$("#ContinueButton").hide();
};
}
})//on
.on('sessionRequestComplete', function(event, id, fileName, responseJSON) {
if ($(this).fineUploader("getNetUploads") > 0){
$("#ContinueButton").show();
};
})//on
.on('deleteComplete', function(event, id, fileName, responseJSON) {
if ($(this).fineUploader("getNetUploads") == 0){
$("#ContinueButton").hide();
};
var submittedFileCount = myUploader.fineUploader("getUploads", {status: qq.status.SUBMITTED});
alert(submittedFileCount);
});//on
$('#ContinueButton').click(function() {
var submittedFileCount = $('#myUploader').fineUploader('getUploads').length
alert(submittedFileCount);
});
}); //close of top script - required
I'm guessing myUploader is the value returned by $("#uploader-container").fineUploader({...});, which is a jQuery object. In that case, you are trying to invoke getUploads on a jQuery object, which of course will not work.
If you want to make this call on the plug-in when using the jQuery wrapper, you'll need to do so like so:
myUploader.fineUploader("getUploads", {status: qq.status.SUBMITTED});
Here is an example of using getNetUploads within the onAllComplete handler with the jQuery uploader:
.on("allComplete", function(responseJSON) {
console.log("allComplete");
if ($(this).fineUploader("getNetUploads") > 0) {
console.log("#ContinueButton.show()");
//$("#ContinueButton").show();
}
else {
console.log("#ContinueButton.hide()");
//$("#ContinueButton").hide();
};
var submittedFileCount = $(this).fineUploader(
"getUploads", {
status: qq.status.SUBMITTED
});
alert(submittedFileCount);
})
The same syntax should apply to any callback handlers your code.
I figured it out. the issue was the filtering of the call. I had it as SUBMITTED and it should have been qq.status.UPLOAD_SUCCESSFUL

Categories

Resources