简体   繁体   English

使用Cropper.js手动裁剪后,将图像直接上传到S3

[英]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... 我是Rails初学者,对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. 我有一个Rails项目,该项目要求用户能够选择一个文件并向其显示预览图像,然后他们可以根据需要进行裁剪,然后再异步上传裁剪后的图像。

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. 我已经使用JQuery FileUpload插件成功实现了直接上传到S3(遵循教程),并且能够向用户显示预览图像,他们可以使用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: 这是我到目前为止用于处理图像裁剪/上载到S3的JS:

$(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. 上面的代码初始化JQuery FileUpload并传递我的S3配置数据。

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: 接下来,我使用JQuery FileUpload的' add '回调来显示预览图像/裁剪框,并在用户单击“上传”按钮时将图像上传到S3:

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. 其余代码主要用于显示上传进度和构建图像URL,我可以将其保存到数据库中以进行图像检索。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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