success remove example dropzone drop and acceptedfiles dropzone.js

dropzone.js - remove - DropZonejs: Enviar formulario sin archivos



dropzone remove file (6)

He integrado exitosamente dropzone.js dentro de un formulario existente. Este formulario publica los archivos adjuntos y otras entradas como casillas de verificación, etc.

Cuando envío el formulario con archivos adjuntos, todas las entradas se publican correctamente. Sin embargo, quiero hacer posible que el usuario envíe el formulario sin ningún archivo adjunto. Dropzone no permite el envío del formulario a menos que haya un archivo adjunto.

¿Alguien sabe cómo puedo anular este comportamiento predeterminado y enviar el formulario dropzone.js sin ningún archivo adjunto? ¡Gracias!

$( document ).ready(function () { Dropzone.options.fileUpload = { // The camelized version of the ID of the form element // The configuration we''ve talked about above autoProcessQueue: false, uploadMultiple: true, parallelUploads: 50, maxFiles: 50, addRemoveLinks: true, clickable: "#clickable", previewsContainer: ".dropzone-previews", acceptedFiles: "image/*,application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.slide, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.template, application/vnd.ms-excel.addin.macroEnabled.12, application/vnd.ms-excel.sheet.binary.macroEnabled.12,text/rtf,text/plain,audio/*,video/*,.csv,.doc,.xls,.ppt,application/vnd.ms-powerpoint,.pptx", // The setting up of the dropzone init: function() { var myDropzone = this; // First change the button to actually tell Dropzone to process the queue. this.element.querySelector("button[type=submit]").addEventListener("click", function(e) { // Make sure that the form isn''t actually being sent. e.preventDefault(); e.stopPropagation(); myDropzone.processQueue(); }); // Listen to the sendingmultiple event. In this case, it''s the sendingmultiple event instead // of the sending event because uploadMultiple is set to true. this.on("sendingmultiple", function() { // Gets triggered when the form is actually being sent. // Hide the success button or the complete form. }); this.on("successmultiple", function(files, response) { window.location.replace(response.redirect); exit(); }); this.on("errormultiple", function(files, response) { $("#notifications").before(''<div class="alert alert-error" id="alert-error"><button type="button" class="close" data-dismiss="alert">×</button><i class="icon-exclamation-sign"></i> There is a problem with the files being uploaded. Please check the form below.</div>''); exit(); }); } } });


Debe comprobar si hay archivos en la cola. Si la cola está vacía, llame directamente a dropzone.uploadFile (). Este método requiere que usted pase un archivo. Como se indica en [caniuse] [1], el constructor de archivos no es compatible con IE / Edge, así que solo use Blob API, ya que File API se basa en eso.

El método formData.append () utilizado en dropzone.uploadFile () requiere que usted pase un objeto que implemente la interfaz Blob. Esa es la razón por la que no puedes pasar en un objeto normal.

La versión 5.2.0 de Dropzone requiere la opción upload.chunked

if (this.dropzone.getQueuedFiles().length === 0) { var blob = new Blob(); blob.upload = { ''chunked'': this.dropzone.defaultOptions.chunking }; this.dropzone.uploadFile(blob); } else { this.dropzone.processQueue(); }


Dependiendo de su situación, simplemente puede enviar el formulario:

if (myDropzone.getQueuedFiles().length > 0) { myDropzone.processQueue(); } else { $("#my_form").submit(); }


El primer enfoque es demasiado caro para mí, no me gustaría profundizar en el código fuente y modificarlo,

Si eres como yo, usa esto.

function submitMyFormWithData(url) { formData = new FormData(); //formData.append(''nameOfInputField'', $(''input[name="nameOfInputField"]'').val() ); $.ajax({ url: url, data: formData, processData: false, contentType: false, type: ''POST'', success: function(data){ alert(data); } }); }

Y en tu script de Dropzone.

$("#submit").on("click", function(e) { // Make sure that the form isn''t actually being sent. e.preventDefault(); e.stopPropagation(); if (myDropzone.getQueuedFiles().length > 0) { myDropzone.processQueue(); } else { submitMyFormWithData(ajaxURL); } });


He utilizado con éxito:

submitButton.addEventListener("click", function () { if(wrapperThis.files.length){ error = `Please select a file`; } else { wrapperThis.processQueue(); } });


Probé la respuesta de Matija Grcic y obtuve el siguiente error:

Uncaught TypeError: Cannot read property ''name'' of undefined

Y no quería modificar el código fuente de Dropzone, así que hice lo siguiente:

if (myDropzone.getQueuedFiles().length > 0) { myDropzone.processQueue(); } else { myDropzone.uploadFiles([{name:''nofiles''}]); //send empty }

Nota: estoy pasando un objeto dentro de la matriz a la función uploadFiles.

Luego verifico el lado del servidor, si el nombre! = ''Nofiles'' carga cosas.


Usa lo siguiente:

$(''input[type="submit"]'').on("click", function (e) { e.preventDefault(); e.stopPropagation(); var form = $(this).closest(''#dropzone-form''); if (form.valid() == true) { if (myDropzone.getQueuedFiles().length > 0) { myDropzone.processQueue(); } else { myDropzone.uploadFiles([]); //send empty } } });

Referencia: https://github.com/enyo/dropzone/issues/418