DropZonejs:提交没有文件的表单

时间:2014-01-03 18:42:04

标签: dropzone.js

我已成功将dropzone.js集成到现有表单中。此表单发布附件和其他输入,如复选框等。

当我提交带有附件的表单时,所有输入都会正确发布。但是,我希望用户可以在没有任何附件的情况下提交表单。 Dropzone不允许表单提交,除非有附件。

有人知道如何覆盖此默认行为并提交dropzone.js表单而没有任何附件吗?谢谢!

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

      }

    }
  });

7 个答案:

答案 0 :(得分:21)

使用以下内容:

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

参考:https://github.com/enyo/dropzone/issues/418

答案 1 :(得分:12)

您应该检查队列中是否有文件。如果队列为空,则直接调用dropzone.uploadFile()。此方法要求您传入文件。正如[caniuse] [1]所述,IE / Edge上不支持File构造函数,因此只需使用Blob API,因为File API就是基于它。

dropzone.uploadFile()中使用的formData.append()方法要求您传递实现Blob接口的对象。这就是你无法传入普通物体的原因。

dropzone版本5.2.0需要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();
}

答案 2 :(得分:11)

根据您的情况,您只需提交表单:

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

答案 3 :(得分:4)

我尝试了Matija Grcic的答案,我收到了以下错误:

Uncaught TypeError: Cannot read property 'name' of undefined

我并不想修改dropzone源代码,所以我做了以下内容:

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

注意:我将数组中的对象传递给uploadFiles函数。

然后我检查服务器端,如果名字!=&#39; nofiles&#39;上传东西。

答案 4 :(得分:1)

第一种方法对我来说太贵了,我不想深入研究源代码并对其进行修改,

如果你碰巧和我一样,请使用它。

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

在你的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);
                        }     

                    });

答案 5 :(得分:0)

我已成功使用:

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

答案 6 :(得分:0)

非常简单,仅当您有要通过Dropzone提交的文件时,才停止传播:

// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
  // Stop the propagation ONLY if you have files to be submitted via Dropzone
  if (myDropzone.getQueuedFiles().length > 0) {
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
  }
});