拖放区。通过Ajax

时间:2018-03-12 23:20:07

标签: jquery ajax typeerror dropzone.js

我有一个通过ajax提交的函数,它通过jQuery从表单中获取值。有多个dropzones,我需要在按下整个表单的提交按钮时抓取它。

我可以像这样访问dropzones文件对象:

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

给我这样的东西:

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, … 

当我尝试将其放入要发送到服务器的对象时,我收到错误:

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

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

如何将此dropzone文件作为图像/文件附加到此处以发送到后端?

2 个答案:

答案 0 :(得分:0)

基于http://api.jquery.com/jquery.ajax/将您的dropzone文件位置添加到数据参数中,如下所示:

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

希望这有帮助

答案 1 :(得分:0)

为了手动将dropzone图像文件发送到后端,我必须创建一个javascript FormData object

例如:

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