kennyg
kennyg

Reputation: 173

Dropzone. Manually upload AcceptedFiles via Ajax

I have a submit function via ajax that get values from a form via jQuery. There are multiple dropzones, which I need to grab from upon pressing the submit button for the entire form.

I can access the dropzones file objects like this:

$('#foobar')[0].dropzone.getAcceptedFiles()[0]

which gives me something like this:

File
​
_removeLink: <a class="dz-remove" href="javascript:undefined;" data-dz-remove="">
​
accepted: true
​
dataURL: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopG…etc"
​
height: 545
​
lastModified: 1516739363000
​
lastModifiedDate: Date 2018-01-23T20:29:23.000Z
​
name: "foobar.jpg"
​
previewElement: <div class="dz-preview dz-image-preview">
​
previewTemplate: <div class="dz-preview dz-image-preview">
​
size: 45960
​
status: "queued"
​
type: "image/jpeg"
​
upload: Object { progress: 0, total: 45960, bytesSent: 0, … }
​
webkitRelativePath: ""
​
width: 550
​
__proto__: FilePrototype { name: Getter, lastModified: Getter, lastModifiedDate: Getter, … 

When I try to put this into an object to send to the server I get the error:

var params = {
  id: $('bla).val(),
  dropzone_image: $('foobar')[0].dropzone.getAcceptedFiles()[0]
}

TypeError: 'click' called on an object that does not implement interface HTMLElement.

How can I attach this dropzone file as an image/file here to send to the backend?

Upvotes: 4

Views: 15369

Answers (2)

kennyg
kennyg

Reputation: 173

In order to send the dropzone image files to the backend manually, I had to create a javascript FormData object.

For example:

function getValues() {
    var formData = new FormData();
    // these image appends are getting dropzones instances
    formData.append('image', $('#foobar_image')[0].dropzone.getAcceptedFiles()[0]); // attach dropzone image element
    formData.append('image_2', $('#barfoo')[0].dropzone.getAcceptedFiles()[0]);
    formData.append("id", $("#id").val()); // regular text form attachment
    formData.append("_method", 'PUT'); // required to spoof a PUT request for a FormData object (not needed for POST request)

    return formData;
}

$(document).on('submit','#form', function(e) {
    e.preventDefault();
    e.stopPropagation();    

    $.ajax({
        method: 'POST',
        url: url/you/want,
        data: getValues(),
        processData: false, // required for FormData with jQuery
        contentType: false, // required for FormData with jQuery
        success: function(response) {
            // do something
        }
    });
});

Upvotes: 3

trueChazza
trueChazza

Reputation: 529

Based on http://api.jquery.com/jquery.ajax/ add your dropzone file location to the data param, like so:

$.ajax({
   url: "location.url",
   data: $('foobar')[0].dropzone.getAcceptedFiles()[0]
}).done(function() {});

Hope this helps

Upvotes: 1

Related Questions