Cancel uploads in onStatusChange - javascript

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!

Related

How to set a limit on the number of uploaded images?

I used ckeditor 5 library for my textarea
I have this JS code
jQuery(function ($) {
ClassicEditor.create(document.querySelector('#history-description'), {
"toolbar": ["imageUpload", "bold", "link", "bulletedList", "uploadImage", "blockQuote"],
"ckfinder": {
"uploadUrl": "uploadImage.php",
"options": {
resourceType: ['jpeg', 'png', 'jpg']
}
},
}).then(editor => {
// editor.plugins.get('FileRepository').on('change:uploadTotal', evt => {
// console.log('Image uploaded evt');
// console.log(evt);
// });
}).catch(error => {
console.error(error);
});
});
How to set a limit on the number of uploaded images?
For example: the maximum number of uploaded files can only be 10

How to open a file chooser inside a function

I am using quill editor and using a image handler for uploading images and it used to work fine but now i am moving to server side rendering and find this error of "File chooser dialog can only be shown with a user activation." while trying to open the file chooser for uploading the file.
imageHandler() {
//
let self=this
let image;
let image_extension;
var input = document.createElement("input");
// Set its type to file
input.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
input.accept = "accept";
// set onchange event to call callback when user has selected file
input.addEventListener("change", onchange)
// dispatch a click event to open the file dialog
input.dispatchEvent(new MouseEvent("click")); //getting the error in this line.
input.onchange = async () => {
//
const file = input.files[0];
var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/jpg", "image/GIF", "image/JPEG", "image/PNG", "image/JPG"];
let file_type = file.type
let filename = file.name
let extension = filename.split('.').pop();
// debugger
if(ValidImageTypes.indexOf(file_type) >= 0){
if(file.size<=500000&&file.size>=50000){
// debugger
var fileToLoad = file
// loadImage(fileToLoad, (canvas) => {
// if(canvas){
// this.setState({
// image=canvas.toDataURL()
// image_extension=extension
// });
this.getBase64(file)
.then(result => {
// debugger
file["base64"] = result;
console.log("File Is",file.base64 );
const res = new Promise(function(resolve, reject) {
axios({
method:'post',
url:API_URL+'api/v1/postblogimage',
headers:{
'x-access-handler':loggedinUser.token
},
data:{
image: file.base64,
image_extension:image_extension,
userid:loggedinUser.userid
}
})
//axios.post(API_URL + 'api/v1/postblogimage', formData, config)
.then((response) => {
if (response.data.error == 'false' || response.data.error == false) {
if (response.data.status == 200 && response.data.message == "Image uploaded successfully") {
//
const range = self.quill.getSelection(true);
// Insert temporary loading placeholder image
// this.quill.insertEmbed(range.index, 'image', `${window.location.origin}/images/loaders/placeholder.gif`);
// Move cursor to right side of image (easier to continue typing)
self.quill.setSelection(range.index + 1);
// Remove placeholder image
self.quill.deleteText(range.index, 1);
// Insert uploaded image
let url=response.data.data[0].imageURL;
self.quill.insertEmbed(range.index, 'image', url);
self.quill.pasteHTML(range.index, <img src={url} class="blog-image-content" alt="Responsive image"/>);
}
}
// else if(response.data.error == 'true' || response.data.status == '500')
// componentProps.error('Sorry, Inappropriate image')
// }
}).catch((error) => {
// reject(Error("It broke"));
});
});
// }
// }, {orientation: true});
// }
})
}
else{
// componentProps.error(" Sorry, File size should be of size between 50 kb to 500kb")
}
}
else{
// this.setState({
// image_warning:'Invalid image type',
// image:'',
// image_extension:''
//})
// this.fileInput.value=''
}
};
}
//render function
<ReactQuill
ref={(el) => this.quillRef = el
}
onChange={this.handleChange}
placeholder={"You can insert images between your blog as well. Max image size to not exceed 500kb.Once you have uploaded an image, just wait, image will show up, if it is approved. Use #hashtags to highlight keywords/impact-terms in your blog, your blog might show up in trending keywords. Example: #gain"}
modules={{
toolbar: {
container: [
[{ header: '1' }, { header: [2,3, 4, 5, 6] }, { font: [] }],
[{ size: [ 'small', false, 'large', 'huge' ] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image', 'video'],
['clean'],
['code-block'],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
],
handlers: {
image: this.imageHandler
}
}
}}
/>
Before you click you must add the input to the document body
document.body.appendChild(input);

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.

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

Fineuploader cancel upload after user response on file submit

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;
}
}
},

Categories

Resources