How do you upload a single image with Dropzone.js?

2019-09-13 01:44发布

问题:

Dropzone.js seems to be uploading images as multi-part form data. How do I get it to upload images in the same way an image upload would work with cURL or a binary image upload with Postman?

I'm getting a pre-signed URL for S3 from a server. The pre-singed URL allows an image upload, but not form fields:

    var myDropzone = new Dropzone("#photo-dropzone");
    myDropzone.options.autoProcessQueue = false;
    myDropzone.options.autoDiscover = false;
    myDropzone.options.method = "PUT";

    myDropzone.on("addedfile", function ( file) {
        console.log("Photo dropped: " + file.name );
        console.log("Do presign URL: " + doPresignUrl);
        $.post( doPresignUrl, { photoName: file.name, description: "Image of something"  })
            .done(function( data ) {
                myDropzone.options.url = data.url
                console.log(data.url);
                myDropzone.processQueue();
        });
    });

If I use the returned URL with Postman and set the body to binary and attach the image, then the upload works fine. However, if the Dropzone library uses the same URL to upload the image to S3 then I get a 403 because S3 does not expect form fields.

Update:

An Ajax alternative works as below with a S3 signed url, but Dropzone.js does not seem willing to put the raw image data in the PUT message body.

            $.ajax( {
                    url: data.url,
                    type: 'PUT',
                    data: file,
                    processData: false,
                    contentType: false,
                    headers: {'Content-Type': 'multipart/form-data'},
                    success: function(){
                        console.log( "File was uploaded" );
                    }
                });

回答1:

Add below options, then working.

myDropzone.options.sending = function(file, xhr) {
  var _send = xhr.send;
  xhr.send = function() {
    _send.call(xhr, file);
  }
}


回答2:

Set maxFiles to 1.

  Dropzone.autoDiscover = false;
        dzAllocationFiles = new Dropzone("div#file-container", {
            url: "api.php?do=uploadFiles"
            , autoDiscover: false
                , maxFiles: 1
                , autoQueue: true
            , addRemoveLinks: true
            , acceptedFiles: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });

        dzAllocationFiles.on("success", function (file, response) {
    // Success Operations
        });

        dzAllocationFiles.on("maxfilesexceeded", function (file, response) {
            allocationFileNames = [];
            this.removeAllFiles();
            this.addFile(file);
        });