DropZonejs: Submit form without files

2020-02-05 01:32发布

I've successfully integrated dropzone.js inside an existing form. This form posts the attachments and other inputs like checkboxes, etc.

When I submit the form with attachments, all the inputs post properly. However, I want to make it possible for the user to submit the form without any attachments. Dropzone doesn't allow the form submission unless there is an attachment.

Does anybody know how I can override this default behavior and submit the dropzone.js form without any attachments? Thank you!

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

      }

    }
  });

标签: dropzone.js
6条回答
Evening l夕情丶
2楼-- · 2020-02-05 01:50

I have successfully used :

submitButton.addEventListener("click", function () {  
  if(wrapperThis.files.length){
        error = `Please select a file`; 
    } else {
        wrapperThis.processQueue(); 
    }
}); 
查看更多
小情绪 Triste *
3楼-- · 2020-02-05 01:57

The first approach is kind of too expensive for me, I would not like to dive into the source code and modify it,

If you happen to be like me , use this.

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

And in your dropzone script

$("#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);
                        }     

                    });
查看更多
▲ chillily
4楼-- · 2020-02-05 01:59

I tried Matija Grcic's answer and I got the following error:

Uncaught TypeError: Cannot read property 'name' of undefined

And I didn't want to modify the dropzone source code, so I did the following:

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

Note: I'm passing an object inside the array to the uploadFiles function.

Then I check server-side, if name != 'nofiles' do upload stuff.

查看更多
▲ chillily
5楼-- · 2020-02-05 02:06

Use the following:

$('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 
                        }                                    
                    }               
                });

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

查看更多
该账号已被封号
6楼-- · 2020-02-05 02:06

You should check if there are files in the queue. If the queue is empty call directly dropzone.uploadFile(). This method requires you to pass in a file. As stated on [caniuse][1], the File constructor isn't supported on IE/Edge, so just use Blob API, as File API is based on that.

The formData.append() method used in dropzone.uploadFile() requires you to pass an object which implements the Blob interface. That's the reason why you cannot pass in a normal object.

dropzone version 5.2.0 requires the upload.chunked option

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();
}
查看更多
再贱就再见
7楼-- · 2020-02-05 02:14

Depending on your situation you could simply submit the form:

if (myDropzone.getQueuedFiles().length > 0) {                        
   myDropzone.processQueue();  
} else {                       
   $("#my_form").submit();
}
查看更多
登录 后发表回答