将blob文件上传到Amazon s3

时间:2015-08-05 11:53:41

标签: angularjs amazon-s3

我正在使用ngCropImage裁剪图片,并希望在this链接后上传:

NgCropImage指令返回图像的dataURI,我将其转换为blob(转换后我得到一个blob对象:具有大小和类型),使用以下代码将DataURI转换为blob:

/*html*/
<img-crop image="myImage" result-image="myCroppedImage" result-image-size="250"></img-crop>

$scope.myImage='';
$scope.myCroppedImage = {image: ''}
var blob;

//called when user crops 
var handleFileSelect=function(evt) {
  var file=evt.currentTarget.files[0];
  var reader = new FileReader();
  reader.onload = function (evt) {
    $scope.$apply(function($scope){
      $scope.myImage=evt.target.result;
    });
  };
  console.log($scope.myCroppedImage)
  reader.readAsDataURL(file);
  var link = document.createElement('link');

  blob = dataURItoBlob($scope.myCroppedImage)
  console.log(blob)
};

angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);


function dataURItoBlob(dataURI) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  var binary = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  var array = [];
  for(var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {type: mimeString});
}

$scope.upload = function(file) {
  //var file = new File(file, "filename");
  // Configure The S3 Object 
  console.log($scope.creds)
  AWS.config.update({ accessKeyId: $.trim($scope.creds.access_key), secretAccessKey: $.trim($scope.creds.secret_key) });
  AWS.config.region = 'us-east-1';
  var bucket = new AWS.S3({ params: { Bucket: $.trim($scope.creds.bucket) } });

  if(file) {
    //file.name = 'abc';
    var uniqueFileName = $scope.uniqueString() + '-' + file.name;
    var params = { Key: file.name , ContentType: file.type, Body: file, ServerSideEncryption: 'AES256' };

    bucket.putObject(params, function(err, data) {
      if(err) {
        // There Was An Error With Your S3 Config
        alert(err.message);
        return false;
      }
      else {
        // Success!
        alert('Upload Done');
      }
    })
    .on('httpUploadProgress',function(progress) {
          // Log Progress Information
          console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
        });
  }
  else {
    // No File Selected
    alert('No File Selected');
  }
} 

$scope.uniqueString = function() {
  var text     = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < 8; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

//for uploading
$scope.handleSave = function(){
  $scope.upload(blob);
}

现在,我想使用this在S3上上传这个blob,但是我无法弄清楚如何将这个blob文件上传到s3(因为我没有在blob文件中获得'name')

任何帮助都会非常感激。感谢

2 个答案:

答案 0 :(得分:5)

您始终可以从blob创建文件。您也可以传递文件名。

var file = new File([blob], "filename");

您可以使用相同的文件对象在s3上传。

将handleSave方法更改为以下内容。文件名现在是abc.png

//for uploading
$scope.handleSave = function(){
  blob = dataURItoBlob($scope.myCroppedImage)
  $scope.upload(new File([blob], "abc.png"));
}

答案 1 :(得分:1)

不建议您放置密钥

  

secretAccessKey:$ .trim($ scope.creds.secret_key)

在客户端......没有完成!任何人都可以随意操纵你的桶。