Non-ajax post using Dropzone.js
Asked Answered
N

4

20

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?

Neysa answered 17/5, 2014 at 21:1 Comment(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/cb4196c25a0ede2b607b17aaef6b930cLamrert
While interesting, this does not seem to stop the Ajax call. I also want the form to submit data for another page to process.Areaway
hi @Areaway , 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 :)Lamrert
T
7

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.

Translucent answered 12/12, 2016 at 21:53 Comment(0)
B
0

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

Bureaucracy answered 20/5, 2014 at 13:13 Comment(6)
This doesn't seem to be stopping the ajax call... what is your use case for this?Neysa
It will not stop the ajax call but you can add others input=file fields to go with your dropzone form if you want. My case was that I needed to send PDF's files through input=file (not using dropzone) and Images though dropzone (which could be sent or not). If my user didn't sent any images my form would be sent normally though POST but if it was added any image it would be sent via AJAX which didn't allowed to send the PDF's files. So I had to do that. I thought it would be you case.Bureaucracy
I see. That's not what I need. I want to use dropzone for the UI, but actually submit the form as it if were using input=file for the images, instead of having dropzone make an ajax call.Neysa
@Neysa I too am interested in knowing if you did?Stgermain
@Neysa I too am interested , did you find a solution about this?Organotherapy
No, I did not. I just changed my approach to make it work with an AJAX call. Sill would love to find a solution.Neysa
C
0

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

Chromatograph answered 29/3, 2016 at 10:40 Comment(2)
This looks very promissing, however when I try it, the inputs added into attachmentsInputContainer seem to be removed from it while processing setupHiddenFileInput function.Areaway
i think the point of this was to upload the files with ajax and then send the filename in a regular form.. if that's what this is, cool, but that's not what the question is asking. the op want to append file to form, which is just not possible.Translucent
A
0

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);
}
}
Ault answered 15/12, 2016 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.