samedi 30 mai 2015

How to create an image file from dataURL to upload to S3?

I am using the JavaScript AWS SDK to upload an image to S3. Before uploading the image, I am resizing using canvas (source: this question).

The resize works well, however I need to create a new file object, like the one obtained from var file = files[0];, that contains the newly resized dataURL.

Files are uploaded to S3 like so:

var params = { Key: fileName, ContentType: file.type, Body: file, ServerSideEncryption: 'AES256' };

bucket.putObject(params, function(err, data) {...}

Replacing Body: file with Body: dataURL results in a corrupted image file that cannot be viewed.

My question is, how can I create a file with the new dataURL that can be uploaded to S3?

I've tried using dataURLtoBlob() to create a blob from a dataURL to be submitted instead of file. The uploaded image file was corrupted and not viewable.

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

...

var newFile = dataURLtoBlob(dataURL);

// send newFile instead of file

Full code:

var files = element[0].files;
var file = files[0];

var img = document.createElement("img");

var reader = new FileReader();
reader.onloadend = function() {
  img.src = reader.result;
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  var MAX_WIDTH = 800;
  var MAX_HEIGHT = 600;
  var width = img.width;
  var height = img.height;

  if (width > height) {
    if (width > MAX_WIDTH) {
      height *= MAX_WIDTH / width;
      width = MAX_WIDTH;
    }
  } else {
    if (height > MAX_HEIGHT) {
      width *= MAX_HEIGHT / height;
      height = MAX_HEIGHT;
    }
  }
  canvas.width = width;
  canvas.height = height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, width, height);

  var dataURL = canvas.toDataURL("image/png");

  // need to send a file object with this new dataURL as a function argument here

};
reader.readAsDataURL(file); 




Aucun commentaire:

Enregistrer un commentaire