最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Non-ajax post using Dropzone.js - Stack Overflow

programmeradmin2浏览0评论

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

Some way to inject the inputs type=file in the DOM right before submit maybe?

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=file in the DOM right before submit maybe?

Share Improve this question edited Dec 9, 2016 at 14:26 Suma 34.4k18 gold badges130 silver badges201 bronze badges asked May 17, 2014 at 21:01 MZAwebMZAweb 3111 gold badge2 silver badges5 bronze badges 3
  • i think the answer from @amandasantnanti is close. But did you try like github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone ? This is gist from my current work before gist.github.com/madaarya/cb4196c25a0ede2b607b17aaef6b930c – Mada Aryakusumah Commented Mar 27, 2015 at 9:26
  • While interesting, this does not seem to stop the Ajax call. I also want the form to submit data for another page to process. – Suma Commented Dec 8, 2016 at 12:43
  • hi @Suma , i have create gist what i did same like your expectation on gist.github.com/madaarya/cb4196c25a0ede2b607b17aaef6b930c . This is still trigger ajax call but with all value on your form too. Hope it help :) – Mada Aryakusumah Commented Dec 11, 2016 at 15:03
Add a comment  | 

4 Answers 4

Reset to default 7 +150

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.

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

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

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)

  1. 暂无评论