Dropzone spinner spins forever after adding file - dropzone.js

Here's a live example, if you upload any file to the dropzone it will just spin forever, tried on multiple browsers:
https://buildgrid.com/bom_supplier_view/ZzrmkDNnx3L0W4NRUYOqVEap4GQXj1bP
I thought turning off autoProcessQueue would fix. Just FYI the files are intended to not be uploaded to the server until the user clicks submit.
var bgDropzone = new dropzone("div#dropzone", {
addRemoveLinks: true,
dictRemoveFile: 'Remove',
url: "/bom_file_upload",
autoProcessQueue: false,
maxFiles: 1,
maxFilesize: 10,
acceptedFiles: ".pdf,.doc,.docx,.xls,.xlsx,.csv,image/*",
createImageThumbnails: false,
maxfilesexceeded: (file) => { // For replacing the current file with another one that was just dropped/selected.
bgDropzone.removeAllFiles();
bgDropzone.addFile(file);
},
dictDefaultMessage: "<i class='fa fa-upload fa-4x'></i><br/><h3>Drag & Drop</h3> files anywhere or <span class='underline'>browse...</span>",
success: (file, response) => {
toastr.success(bgDropzone.options.params.toast_text, '', {
onHidden: () => {
window.location.href = "/bom/" + bgDropzone.options.params.bom_id;
}
});
},
error: (file, errorMessage, xhr) => {
if (xhr) {
toastr.error('There was an error processing your request: ' + errorMessage, '');
}
},
uploadProgress: (progress) => {
bgDropzone.querySelector("#total-progress .progress-bar").style.width = progress + "%";
}
})
.on('addedfile', (file) => {
var bomName = file.name.toString().toLowerCase()
.replace(/\.[^/.]+$/, "")
.replace(/[_-]/g, ' ')
.replace(/(?:^|\s)\S/g, (a) => {
return a.toUpperCase();
});
$('input[name=bom_name]').val(bomName);
$('input[name=filename]').val(file.name.toString());
});
// Removes error state styling from form fields and the Dropzone.
function removeErrorStyles() {
$('.form-group').removeClass('has-error');
$('div#dropzone').css('border', '3px dashed #0076be');
$('div#notifications').hide();
}

Related

jquery validation file input doesnot work [duplicate]

This question already has answers here:
Jquery file validation
(5 answers)
Closed 2 years ago.
Hi i have a html form with an input file and many more fields .I am going to validate it by jquery form validator plugin . It works like a charm for text inputs and selects but it just validate file input when it is empty. When I choose a file in any wrong type or wrong size , even if I didn't filled other required text input , it submit the form in GET method.this is my jquery code:
$("#form").validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-error-label',
successClass: 'validation-valid-label',
highlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function (error, element) {
// Styled checkboxes, radios, bootstrap switch
if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container')) {
if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent().parent().parent());
} else {
error.appendTo(element.parent().parent().parent().parent().parent());
}
}
// Unstyled checkboxes, radios
else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
error.appendTo(element.parent().parent().parent());
}
// Input with icons and Select2
else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo(element.parent());
}
// Inline checkboxes, radios
else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent());
}
// Input group, styled file input
else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
error.appendTo(element.parent().parent());
}
// Inline checkboxes, radios
// else if (element.parents().hasClass('uploader')) {
// error.appendTo(element.parent().parent().parent().parent());
// }
else {
error.insertAfter(element);
}
},
validClass: "validation-valid-label",
success: function (label) {
label.addClass("validation-valid-label").text("معتبر.")
},
rules: {
title: {
required: true,
minlength: 8
},
unique_name: {
required: true,
minlength: 3
},
lang: {
required: true,
},
style: {
required: true,
},
image01: {
required: true,
// extension: "gif|png|jpg|jpeg", // work with additional-mothods.js
accept: "image/jpeg, image/pjpeg",
filesize: 1000000, // 1MB, this filesize method is the custom method that I create. the code can be found in this post.
}
},
messages: {
image01: {
require: "لطفا لوگوی سایت را انتخاب نمایید",
filesize: "حجم مجاز فایل ۱ مگابایت می باشد",
extension: "فرمت مجاز فایل jpeg,gif,png می باشد"
},
title: {
required: "لطفا فیلد را با حداقل 8 کاراکتر کامل نمایید",
},
unique_name: {
required: "لطفا فیلد مورد نظر را کامل کنید",
minlength: "حداقل ۳ کاراکتر.کاراکترها بهتر است انگلیسی باشد"
},
lang: {
required: "لطفا زبان مورد نظر را انتخاب نمایید",
},
style: {
required: "لطفا قالب مورد نظر را انتخاب نمایید",
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
//enctype: 'multipart/form-data',
url: "/admin/{{ CURRENTCLASS }}/fullInsert",
data: new FormData($("#form")[0]),
datatype: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
//$("#loaderDiv").show();
},
success: function (result) {
result = $.parseJSON(result);
if (result.dataUpload === true && result.imageUpload === true) {
$('#modalheader').removeClass().addClass('modal-header bg-success');
$('.modal-title').html("ثبت اطلاعات");
$('#modal-msg').html(result.dataEntryMsg);
$('form')[0].reset();
} else if (!result.dataUpload) {
$('#modalheader').removeClass().addClass('modal-header bg-danger');
$('.modal-title').html("خطا در ثبت اطلاعات");
$('#modal-msg').html(result.dataEntryMsg);
$('form')[0].reset();
} else if (result.dataUpload == true & result.imageUpload == false) {
$('#modalheader').removeClass().addClass('modal-header bg-warning');
$('.modal-title').html("خطا در ثبت تصویر");
$('.modal-body').html(result.dataEntryMsg + "<br>" + result.imgUploadMsg);
}
$('#modal_theme').modal('toggle');
},
complete: function () {
//$("#loaderDiv").hide();
},
error: function (result) {
// alert('4');
// $('#modal_theme').modal('toggle');
// $("#loaderDiv").hide();
// $('.modal-body').html(result.msg);
// $('#delModal').modal('toggle');
}
});
return false; // required to block normal submit since you used ajax
}
});
after deep searching i found what is the problem. To validate extensions with jquery validation plugin you must include additional_methods.js file.it must be added after validate.js file. Hope it help you.

Uppy + Laravel can't upload file

Trying to use Uppy JS lib to upload file throug Laravel. Setted up simple upload form with there params:
const options = {
endpoint: '/parts/image-upload',
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
};
uppyDashboard.use(XHRUpload, options);
And on the backend I'm getting
Illuminate\Contracts\Encryption\DecryptException: The payload is invalid. in file /Users/rd/Projects/xxx/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php on line 195
It's like Laravel trying to decrypt something what is already decrypted, anyway I'm in dead end.
You can this code
var uppy = new Uppy.Core({
// debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
// warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
// error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
autoProceed: true,
restrictions: {
maxFileSize: 2000000,
maxNumberOfFiles: 10,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*']
}
});
uppy.use(Uppy.Dashboard, {
target: ".UppyDragDrop",
inline: true,
showLinkToFileUploadResult: false,
showProgressDetails: true,
hideCancelButton: true,
hidePauseResumeButton: true,
hideUploadButton: true,
proudlyDisplayPoweredByUppy: false,
locale: {} });
Here's how I implemented it
<script type="text/javascript">
$(document).ready(function() {
$('[id*=drag-drop-area]').each(function(){
var listing_id = $(this).attr('class');
var uppy = new Uppy.Core({
allowMultipleUploadBatches: true,
restrictions: {
maxFileSize: 100000000,
// maxNumberOfFiles: 8,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png']
}
})
.use(Uppy.Dashboard, {
inline: true,
target: "#"+$(this).attr('id')+""
})
.use(Uppy.XHRUpload, {
endpoint: 'upload',
formData: true,
bundle: true,
headers: {
'X-CSRF-Token': " {{ csrf_token() }} "
},
});
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
});
});
</script>
You create the endpoint which is the route name and attach at
endpoint: ""
Then you return a response which you grab and do whatever on the last section.
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
I hope this helps

Dropzone.js - remove preview file if upload fails

I have a problem with my dropzone,
$(".js-example-basic-multiple").select2();
Dropzone.options.dropZone = {
//options here
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: host+'upload/unfile',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
//console.log();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
}
My problem is, when a file fails to upload, it still shows the preview images, so i need that file to be removed automatically when these file fails to upload, how can I do that??
I think, if I understand you correctly, you can just delete the image with this code:
Dropzone.options.dropZone = {
...
, error: function(file, message, xhr) {
$(file.previewElement).remove();
},
...
}
Just read the documentation again.
This code is from the docs:
myDropzone.on("error", function(file) {
myDropzone.removeFile(file);
});
Please let me know, if it works in your case.
When connect error is "xhr.ontimeout", function "error:" don't run.
I need (paste next to "init:"):
sending: function(file, xhr, formData) {
//Execute on case of timeout only
xhr.ontimeout = function(e) {
alert('connection interrupted');
};
}

Dropzonejs: Attempted to redefine property 'filesizeBase'

I've integrated DropzoneJs into a VueJs application im putting together. It's running great in both Chrome and Firefox but for some reason the app is very sad in safari. I'm getting the following error in Safari: Attempted to redefine property 'filesizeBase'.
My Vue Component Looks as Follows:
var Dropzone = require('../../vendor/dropzone.min.js');
module.exports = {
template: require('./views/files.html'),
props: ['files', 'is-complete'],
data: function()
{
return {
reverse: -1,
uploading: false,
token: document.querySelector('#token').getAttribute('value'),
project: document.querySelector('#project').getAttribute('value'),
}
},
methods: {
uploadFile: function(e)
{
e.preventDefault();
var self = this;
this.uploading = !this.uploading;
if(this.uploading)
{
var myDropzone = new Dropzone("form#mediaUpload", {
init: function() {
this.on("complete", function(file) {
setTimeout(function()
{
self.uploading = false;
}, 5000);
});
this.on("success", function(file, uploadedFile) {
self.files.push(uploadedFile);
});
},
paramName: "file",
maxFilesize: 250, // MB
maxFiles: 15,
uploadMultiple: false,
});
}
},
deleteFile: function(file, index)
{
this.files.pop(index);
this.$nextTick(function()
{
this.$http.post('/upload/'+file.id+'/delete');
});
},
},
components: {
fileSize: require('./FileSize'),
humanTime: require('../Helpers/HumanTime'),
mimeType: require('../Helpers/MimeType'),
}
}

How to dynamically change event sources?

I am using the jQuery FullCalendar plug-in. I want to load initially the calendar with events as an array. I am doing this like:
events: <%= Model.Events %>
or
eventSources: [{
events: <%= Model.Events %>
}]
Both ways work fine. I am using MVC 3.0 and <%= Model.Events %> returns an array of events in JSON format.
I want to use the events array ONLY for the initial loading of the calendar. Later, every times events are needed to be fetched, I want my events to be loaded using the url '/Calendar/Events'.
How can be this implemented?
I tried difference scenarios with addEventSource/removeEventSource in the viewDisplay callback, but nothing worked fine for me.
.fullCalendar( {
eventSources : [ {
url : '/Calendar/Events',
type : 'GET'
} ],
viewDisplay : function( event ) {
// assuming this will point to the full calendar,
// might have to do something silly like
// $( '#myCal' ).fullCalendar( 'refetchEvents' );
this.refetchEvents();
}
} );
I know it's a very old question but I needed this right now. The answer wasn't here but I found it in another question.
Here what is solution.
My primary source of events is this(this is the events source from the default examples of Fullcalendar):
events: function(start, end, callback) {
$.ajax({
type: 'POST',
url: 'myurl',
dataType:'xml',
crossDomain: true,
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
'acc':'2',
},
success: function(doc) {
var events = [];
var allday = null; //Workaround
var Editable = null; //Workaround
$(doc).find('event').each(function()
{
if($(this).attr('allDay') == "false") //Workaround
allday = false; //Workaround
if($(this).attr('allDay') == "true") //Workaround
allday = true; //Workaround
if($(this).attr('editable') == "false") //Workaround
Editable = false; //Workaround
if($(this).attr('editable') == "true") //Workaround
Editable = true; //Workaround
events.push({
id: $(this).attr('id'),
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
allDay: allday,
editable: Editable
});
});
//calendar.fullCalendar( 'addEventSource', othersources.folgas );
//calendar.fullCalendar( 'addEventSource', othersources.ferias );
//calendar.fullCalendar('refetchEvents');
callback(events);
}
});
}
Now i needed it to add more sources and to do this ouside the calendar (next to the date variables from fullcalendar examples) i made a variable like the code above, but with ajax calls similar to my primary: )
var othersources = {
anothersource: {
events: function(start, end, callback) {
$.ajax({
type: 'POST',
url: 'myurl',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
'acc':'7',
},
success: function(doc) {
var events = [];
var allday = null; //Workaround
var Editable = null; //Workaround
$(doc).find('event').each(function()
{
if($(this).attr('allDay') == "false") //Workaround
allday = false; //Workaround
if($(this).attr('allDay') == "true") //Workaround
allday = true; //Workaround
if($(this).attr('editable') == "false") //Workaround
Editable = false; //Workaround
if($(this).attr('editable') == "true") //Workaround
Editable = true; //Workaround
events.push({
id: $(this).attr('id'),
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
allDay: allday,
editable: Editable
});
});
callback(events); //notice this
}
});
},
cache: true,
//error: function() { alert('something broke with courses...'); },
color: 'green', //events color and stuff
textColor: 'white',
//className: 'course'
}
}
Now, he build diffrent sources and use like this both...
eventSources: [ othersources.anothersource ],
viewDisplay: function(view) {
if (view.name == 'month'){
calendar.fullCalendar( 'addEventSource', othersources.anothersource );
//calendar.fullCalendar('refetchEvents');
//Notice i'm not doing the refetch events. And its working for me. but i'm calling thi elsewhere, every time i make an action. So you must figure it out ;)
}
Link to above solution
And another way i found on github.
Basically the problem was that I can't change data parameters after calendar initialization. For events this worked:
events: {
url : '',
type: 'POST',
data: function () {
return {
action: 'view',
search_text: search_text
};
},
error: function() {
alert('there was an error while fetching events!');
},
color: '#31b0d5', // a non-ajax option
textColor: '#fff;', // a non-ajax option
},
for resources it didnt so I had to make like that:
resources: function(callback) {
var view = $("#calendar").fullCalendar("getView");
$.ajax({
url: "",
type: 'POST',
dataType: "json",
cache: false,
data: {
start : view.start.format(),
end : view.end.format(),
timezone : view.options.timezone,
action : 'projects_employees',
search_text: search_text
}
}).then(function(resources) {
callback(resources);
})
},
Simple ways like that do not work cuz are static and couldn't be changed after init:
events: {
url: '',
type: 'POST',
data: {
action: 'view',
search_text: search_text
}
},
resources: {
url: '',
type: 'POST',
data: {
action: 'projects_employees',
search_text: search_text
}
}
Here is the github link. Replied by peon501.
After to many try, i did solve my problem with use first part (stackoverflow) codes. The key for me defiying eventSource with "var" key and use it like this
//...
eventSources: [ othersources.anothersource ] ,
//...
I have collected all the data in a php file the way I want it. And the output of this page was a javascript with this
header('Content-Type: text/javascript');
$fromDB ="";
$sources = "sources = [";
foreach ($events as $value) { // value is source name
$fromDB .= "var $value = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
";
$sources .= $value. " ";
}
$sources .= " ];";
// this $sources give me
// sources = [anothersource ,othersource ,anothersource2 ];
This make like this
var anothersource = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
var othersource = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
var anothersource2 = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
sources = [anothersource ,othersource ,anothersource2 ];
.fullCalendar( {
eventSources : sources , // here, we use dynamic eventsources
viewDisplay : function( event ) {
// assuming this will point to the full calendar,
// might have to do something silly like
// $( '#myCal' ).fullCalendar( 'refetchEvents' );
this.refetchEvents();
}
} );
I added the main javascript file, which will do all the operations, at the bottom of this php file.
//...
$file = "my/fullcalender/initjavascript/file.js"
file_get_contents($file) . PHP_EOL;
//...
This code opens the javascript file in the $file path and takes whatever is in it and adds it to this file.
I hope that will be useful.

Resources