简体   繁体   中英

Direct Upload of Image to S3 after Manual Cropping with Cropper.js

This is my first post, so be gentle! I'm a Rails beginner and clueless with JavaScript/JQuery...

I have a Rails project which requires that the user be able to select a file and be presented with a preview image, which they can then crop as they wish before uploading the cropped image asynchronously.

I have successfully implemented direct upload to S3 using the JQuery FileUpload plugin (following this tutorial) and I am able to present the user with a preview image which they can crop using Cropper.js. However I need help with the last step of uploading the cropped image.

Here is the JS I have so far for handling the image crop/upload to S3:

$(document).ready(function() {
  $('.directUpload').find("input:file").each(function(i, elem) {
    var fileInput    = $(elem);
    var form         = $(fileInput.parents('form:first'));
    var submitButton = form.find('input[type="submit"]');
    var progressBar  = $("<div class='bar'></div>");
    var barContainer = $("<div class='progress'></div>").append(progressBar);
    fileInput.after(barContainer);

    fileInput.fileupload({
      fileInput:        fileInput,
      url:              form.data('url'), //read AWS config via form attributes
      type:             'POST',
      autoUpload:       false, // prevent upload start on file selection
      formData:         form.data('form-data'), 
      paramName:        'file', 
      dataType:         'XML',  
      replaceFileInput: false,

The code above initializes JQuery FileUpload and passes my S3 configuration data.

Next I use the JQuery FileUpload's ' add ' callback to display a preview image/cropbox, and to upload the image to S3 when the user clicks an 'Upload' button:

add: function (e, data) {
  if (data.files && data.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#preview_image').attr('src', e.target.result); // insert preview image
      $('#preview_image').cropper() // initialize cropper on preview image
     };
   reader.readAsDataURL(data.files[0]); 
  };

  $('#upload_image').on('click', function(){
    $('#preview_image').cropper('getCroppedCanvas').toBlob(function (blob){
      var croppedFile = new File([blob], 'cropped_file.png')
      // How do I now get my cropped file data to upload instead of original file?
    })
    data.submit();
  });
},

It is the last part, above, where I am now stuck - I've created a file from the cropped area, but have been unable to find a way to upload it instead of the original image.

The remaining code deals mainly with displaying upload progress and building an image URL that I can save to my database for image retrieval.

progressall: function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
    progressBar.css('width', progress + '%')
  },

  start: function (e) {
    submitButton.prop('disabled', true); //disable submit button while image is loading

    progressBar.
      css('background', 'green').
      css('display', 'block').
      css('width', '0%').
      text("Loading...");
  },

  done: function(e, data) {
    submitButton.prop('disabled', false);
    progressBar.text("Uploading done");

    // extract key from S3 XML response and generate URL for image
    var key   = $(data.jqXHR.responseXML).find("Key").text();
    var url   = '//' + form.data('host') + '/' + key;

    // create hidden field containing image URL, which can then be stored in model
    var input = $("<input />", { type:'hidden', name: 'image_url[]', value: url })
    form.append(input);
  },

  fail: function(e, data) {
    submitButton.prop('disabled', false);

    progressBar.
      css("background", "red").
      text("Failed");
  }
});

This worked for me

var croppedFile = new File([blob], 'cropped_file.png');    
data.files[0] = croppedFile;
data.originalFiles[0] = data.files[0];

or just

data.files[0] = new File([blob], 'cropped_file.png');
data.originalFiles[0] = data.files[0];

and then

data.submit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM