Reset FilePond Input in Javascript - 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.

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

Display notification pop-up box on open-source CRM

I am using a vtiger Crm system and I would like to use the pop up notification to display my own messages. I wrote an event handler that triggers after model save, in this handler I would like to call the notification box with my own message.
Here is a working example that is from the 'Products' module handlers, this code was pre-written, it checks if there were duplicate item numbers and shows a message 'LBL_DUPLICATE_item_number' in the pop-up box
class Products_DuplicateItemNumber_Handler
{
/**
* EditViewPreSave handler function.
*
* #param App\EventHandler $eventHandler
*/
public function editViewPreSave(App\EventHandler $eventHandler)
{
$recordModel = $eventHandler->getRecordModel();
$response = ['result' => true];
$fieldModel = $recordModel->getModule()->getFieldByName('item_number');
if ($fieldModel->isViewable() && ($item_number = $recordModel->get('item_number'))) {
$queryGenerator = new \App\QueryGenerator($recordModel->getModuleName());
$queryGenerator->setStateCondition('All');
$queryGenerator->setFields(['id'])->permissions = false;
$queryGenerator->addCondition($fieldModel->getName(), $item_number, 'e');
if ($recordModel->getId()) {
$queryGenerator->addCondition('id', $recordModel->getId(), 'n');
}
if ($queryGenerator->createQuery()->exists()) {
$response = [
'result' => false,
'hoverField' => 'item_number',
'message' => App\Language::translate('LBL_DUPLICATE_item_number', $recordModel->getModuleName())
];
}
}
return $response;
}
}
However, when i try to return $respone in 'editViewPreSave' of another module, nothing happens.
After some digging around i found out that the system uses 'Pnotify' library to show the pop up message, and i belive it's being called in a js file called 'edit.js' in this path 'public_html/layouts/basic/modules/Vtiger/resources'
preSaveValidation: function (form) {
const aDeferred = $.Deferred();
if (form.find('#preSaveValidation').val()) {
document.progressLoader = $.progressIndicator({
message: app.vtranslate('JS_SAVE_LOADER_INFO'),
position: 'html',
blockInfo: {
enabled: true
}
});
let formData = new FormData(form[0]);
formData.append('mode', 'preSaveValidation');
AppConnector.request({
async: false,
url: 'index.php',
type: 'POST',
data: formData,
processData: false,
contentType: false
})
.done((data) => {
document.progressLoader.progressIndicator({ mode: 'hide' });
let response = data.result;
for (let i = 0; i < response.length; i++) {
if (response[i].result !== true) {
app.showNotify({
text: response[i].message ? response[i].message : app.vtranslate('JS_ERROR'),
type: 'error'
});
if (response[i].hoverField != undefined) {
form.find('[name="' + response[i].hoverField + '"]').focus();
}
}
}
aDeferred.resolve(data.result.length <= 0);
})
.fail((textStatus, errorThrown) => {
document.progressLoader.progressIndicator({ mode: 'hide' });
app.showNotify({
text: app.vtranslate('JS_ERROR'),
type: 'error'
});
app.errorLog(textStatus, errorThrown);
aDeferred.resolve(false);
});
} else {
aDeferred.resolve(true);
}
return aDeferred.promise();
},
I believe that 'app.showNotify' is the function called to display the pop-up box, yet i'm not sure how to replicate the code for my own use, i would like to know the best approach to do this

React Dropzone Component - How to dynamically change postUrl?

I am using react dropzone component https://github.com/felixrieseberg/React-Dropzone-Component to facilitate the dragging and dropping of files onto a site.
I want each file that gets dropped onto the dropzone to get posted to a different url (AWS Pre-Signed URL). Essentially I want the the component config parameter 'postUrl' to dynamically change as this pre-signed URL changes.
I currently have the following component configuration set
class Uploader extends React.Component {
constructor(props){
super(props);
this.dropzone = 'null'
}
config = () => (
{
iconFiletypes: ['.jpg', '.png', '.gif'],
showFiletypeIcon: true,
postUrl: this.dropzone.options.url || 'no-url'
}
);
eventHandlers = () => (
{
processing: function(file) {
},
init: dz => this.dropzone = dz,
}
);
djsConfig = (requestID=this.props.requestId) => (
{
addRemoveLinks: false,
acceptedFiles: "image/jpeg,image/png,image/gif",
autoProcessQueue: true,
init: function () {
this.on("processing", async (file) => {
const presigned_url = await uploadUrl(file, requestID, () => {})
this.options.url = presigned_url;
});
}
}
);
}
I get the following error when I load the page/component:
Uncaught TypeError: Cannot read property 'url' of undefined
Updating the options.url on the Dropzone object via djsConfig when a file is processed doesn't get the chance to update the postUrl: this.dropzone.options.url as I would like?
As commented by lex.
Change your init method as below:
init:function () {
var _this=this;
this.on("processing", async (file) => {
const presigned_url = await uploadUrl(file, requestID, () => {})
_this.options.url = presigned_url;
});
}

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!

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