繁体   English   中英

无法使用node.js和angular将图像Blob上传到AWS S3

[英]Unable to upload image blob to AWS S3 using node.js & angular

我无法将图像上传到AWS S3

{[[InvalidParameterType:期望的params.body是字符串,缓冲区,流,Blob或类型的数组对象]消息:'期望的params.body是一个字符串,Buffer,Stream,Blob或类型化的数组对象,” 'InvalidParameterType',

背景信息因此,这就是我想要做的事情:首先,我使用Angular Image Cropper( http://andyshora.com/angular-image-cropper.html )将图像裁剪为可接受的移动尺寸。 这给出了base64 URI。

然后,我使用dataURItoBlob将URI转换为blob,然后尝试上传到AWS S3。

代码如下:

$scope.dataURItoBlob= function(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}


$scope.uploadPic = function() {
    var base64data = document.getElementById('base64').value;

    console.log("the data is: "+ base64data);
    $scope.pic.Body = $scope.dataURItoBlob(base64data);
    console.log("the blob is: "+ $scope.pic.Body);

    $http({
    method: 'POST',
    url: '/api/upload/picture',
    data: $scope.pic
  }).success(function (data) {
    //success code
  });

};  

节点(后端)

exports.uploadPicture = function (req, res) {
        if (!req.body.hasOwnProperty('Key') || !req.body.hasOwnProperty('Body')) {
            res.statusCode = 400;
            return res.send('Error 400: Post syntax incorrect.');
        } else {
            var key = req.body.Key;
            var body = req.body.Body;

            AWS.config.loadFromPath('./config.json');

            var s3 = new AWS.S3(); 
            s3.createBucket({Bucket: 'bucket'}, function() {
              var params = {Bucket: 'bucket', Key: key, Body: body};
              s3.putObject(params, function(err, data) {
              if (err) {
              console.log(err);
                res.status(400).send('Bad Request.');
              } else {
                console.log("Successfully uploaded data to myBucket/myKey");   
              }
            });
            });
        }

}

它失败,因为它期待一个Blob,但是它拒绝了我发送的Blob。请帮助!

谢谢!

您的“ var base64data”里面有什么?

尝试这个:

 buf = new Buffer(req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),'base64')
  var data = {
    Key: req.body.userId, 
    Body: buf,
    ContentEncoding: 'base64',
    ContentType: 'image/jpeg'
  };
  s3Bucket.putObject(data, function(err, data){
      if (err) { 
        console.log(err);
        console.log('Error uploading data: ', data); 
      } else {
        console.log('succesfully uploaded the image!');
      }
  });

希望能有所帮助

暂无
暂无

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

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