类型错误:无法读取未定义的属性“byteLength” - AWS S3 上传

IT技术 reactjs amazon-web-services amazon-s3 aws-sdk
2021-05-23 11:34:21

我正在处理来自 React 客户端的 aws s3 照片上传,但遇到以下错误:

TypeError: Cannot read property 'byteLength' of undefined

我假设上传对象存在缺陷,但我相信 s3/cognito 配置可能有问题,因为我在调用s3.listObjects. 我正在关注这些文档 - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album-full.html

有什么想法吗?

uploadPhoto() {
        const files = document.getElementById("photoUpload").files;
        if (!files.length) {
          return alert("Please choose a file to upload first.");
        }
        const file = files[0];
        const fileName = file.name;
        const albumPhotosKey = encodeURIComponent('screenshots') + "/";
      
        const photoKey = albumPhotosKey + fileName;
        
        // Use S3 ManagedUpload class as it supports multipart uploads
        
        const upload = new AWS.S3.ManagedUpload({
            params: {
              Bucket: <Bucket Name>,
              Key: fileName,
              Body: file
            }
          });

        const promise = upload.promise();
      
        promise.then(
          function(data) {
            alert("Successfully uploaded photo.");
            console.log('UPLOAD: ', data)
          },
          function(err) {
              console.log('ERROR: ', err)
            // return alert("There was an error uploading your photo: ", err.message);
          }
        );
      }
3个回答

我在 React Native 应用程序中遇到了这个错误。我可以通过关闭我的开发工具网络检查器来修复它。

我已经按照文档中的描述运行了示例并且它可以工作,因此无法重现您的错误。这里有几件事要检查:

  • 尝试将您的访问密钥和秘密传递到您的配置对象中(尽管出于安全原因我不建议这样做,但它可能表明问题出在哪里):
AWSService.config.update({
    region: region,
    accessKeyId: accessKeyId,
    secretKey: secretAccessKey,
    credentials: new AWSService.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId
    })
});

  • 确认您的 Cognito 身份池 ID 具有 IAM 策略,并附有以下内容:
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME",
                "arn:aws:s3:::BUCKET_NAME/*"
            ]
        }
    ]
}

以防万一!检查您的凭据是否已配置并正确传递。并且您拥有 IAM 中资源的权限。

我有上面的错误,因为我忘记传递访问凭据。一旦我把它们放进去它就消失了。