Non-ajax post using Dropzone.js

后端 未结 4 1303
一生所求
一生所求 2020-12-10 11:21

I\'m wondering if there\'s any way to make Dropzone.js (http://dropzonejs.com) work with a standard browser POST instead of AJAX.

Some way to inject the inputs type=

相关标签:
4条回答
  • 2020-12-10 12:02

    So, if I understood correctly you want to append some data (input=file) before submit your form which has dropzone activated, right?

    If so, I had to do almost the same thing and I got it through listening events. If you just upload one file, you should listen to "sending" event, but if you want to enable multiple uploads you should listen to "sendingmultiple". Here is a piece of my code that I used to make this work:

    Dropzone.options.myAwesomeForm = {
      acceptedFiles: "image/*",
      autoProcessQueue: false,
      uploadMultiple: true,
      parallelUploads: 100,
      maxFiles: 100,
    
      init: function() {
        var myDropzone = this;
    
        [..some code..]
    
        this.on("sendingmultiple", function(files, xhr, formData) {
          var attaches = $("input[type=file]").filter(function (){
            return this.files.length > 0;
          });
    
          var numAttaches = attaches.length;
    
          if( numAttaches > 0 ) {
            for(var i = 0; i < numAttaches; i++){  
              formData.append(attaches[i].name, attaches[i].files[0]);
              $(attaches[i]).remove();
            }
          }
        });
    
        [..some more code..]
    
      }
    }
    

    And that's it. I hope you find it helpful :)

    PS: Sorry if there's any grammar mistakes but English is not my native language

    0 讨论(0)
  • 2020-12-10 12:06

    For future visitors I've added this to dropzone options:

    addedfile: function (file) {
                var _this = this,
                        attachmentsInputContainer = $('#attachment_images');
                file.previewElement = Dropzone.createElement(this.options.previewTemplate);
                file.previewTemplate = file.previewElement;
                this.previewsContainer.appendChild(file.previewElement);
                file.previewElement.querySelector("[data-dz-name]").textContent = file.name;
                file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size);
                if (this.options.addRemoveLinks) {
                    file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
                    file._removeLink.addEventListener("click", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        if (file.status === Dropzone.UPLOADING) {
                            return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function () {
                                return _this.removeFile(file);
                            });
                        } else {
                            if (_this.options.dictRemoveFileConfirmation) {
                                return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function () {
                                    return _this.removeFile(file);
                                });
                            } else {
                                return _this.removeFile(file);
                            }
                        }
                    });
                    file.previewElement.appendChild(file._removeLink);
                }
                attachmentsInputContainer.find('input').remove();
                attachmentsInputContainer.append(Dropzone.instances[0].hiddenFileInput).find('input').attr('name', 'files');
                return this._updateMaxFilesReachedClass();
            },
    

    This is default implementation of dropzone's addedfile option with 3 insertions.

    Declared variable attachmentsInputContainer. This is invisible block. Something like

    <div id="attachment_images" style="display:none;"></div>
    

    Here I store future input with selected images Then in the end of function remove previously added input(if any) from block and add new

    attachmentsInputContainer.find('input').remove();
    attachmentsInputContainer.append(Dropzone.instances[0].hiddenFileInput).find('input').attr('name', 'files');
    

    And now, when you send form via simple submit button, input[name="files"] with values will be send.

    I've made this hack because I append files to post that maybe not created yet

    0 讨论(0)
  • 2020-12-10 12:19

    No. You cannot manually set the value of a <input type='file'> for security reasons. When you use Javascript drag and drop features you're surpassing the file input altogether. Once a file is fetched from the user's computer the only way to submit the file to the server is via AJAX.

    Workarounds: You could instead serialize the file or otherwise stringify it and append it to the form as a string, and then unserialize it on the server side.

    var base64Image;
    var reader  = new FileReader();
    reader.addEventListener("load", function () {
        base64Image = reader.result;
        // append the base64 encoded image to a form and submit
    }, false);
    reader.readAsDataURL(file);
    

    Perhaps you're using dropzone.js because file inputs are ugly and hard to style? If that is the case, this Dropzone.js alternative may work for you. It allows you to create custom styled inputs that can be submitted with a form. It supports drag and drop too, but with drag and drop you cannot submit the form the way you want. Disclaimer: I am author of aforementioned library.

    0 讨论(0)
  • 2020-12-10 12:19

    This is what I used for my past projects,

    function makeDroppable(element, callback) {
    
    var input = document.createElement('input');
    
    input.setAttribute('type', 'file');
    
    input.setAttribute('multiple', true);
    
    input.style.display = 'none';
    
    input.addEventListener('change', triggerCallback);
    
    element.appendChild(input);
    
    element.addEventListener('dragover', function(e) {
    
    e.preventDefault();
    
    e.stopPropagation();
    
    element.classList.add('dragover');
    });
    
    element.addEventListener('dragleave', function(e) {
    
    e.preventDefault();
    
    e.stopPropagation();
    
    element.classList.remove('dragover');
    });
    
    element.addEventListener('drop', function(e) {
    
    e.preventDefault();
    
    e.stopPropagation();
    
    element.classList.remove('dragover');
    
    triggerCallback(e);
    });
    
    element.addEventListener('click', function() {
    input.value = null;
    input.click();
    });
    
    function triggerCallback(e) {
    
      var files;
    
      if(e.dataTransfer) {
    
      files = e.dataTransfer.files;
    
    } else if(e.target) {
    
      files = e.target.files;
    }
    callback.call(null, files);
    }
    }
    
    0 讨论(0)
提交回复
热议问题