如何从 Angular 8 在 AWS S3 中上传文件

Rus*_*dhu 8 amazon-s3 angular angular8

我在从 Angular 8 Project 上传文件到 S3 时遇到错误。我已按照以下教程进行操作并执行所需的操作

https://medium.com/ramsatt/angular-7-upload-file-to-amazon-s3-bucket-ba27022bad54

但我无法在服务文件中使用 S3 库。

错误截图

下面几行产生了我认为但仍然不确定哪里缺少东西的错误

从“aws-sdk/global”导入 * 作为 AWS;

从 'aws-sdk/clients/s3' 导入 * 作为 S3;

有没有人可以帮我摆脱它。

Rus*_*dhu 6

在花了几个小时之后,我终于提出了解决方案。Angular 8 项目的解决方案步骤如下。

  1. 安装依赖

    npm install --save-dev @types/node

  2. 需要将 "types": ["node"] 添加到 tsconfig.app.json

  3. 在 polyfills.js 中添加以下几行

    if (typeof (window as any).global === 'undefined') { (window as any).global = window; }
    
    Run Code Online (Sandbox Code Playgroud)

参考:@AWS PS 的最后回答(步骤 1)
参考:https : //github.com/aws/aws-sdk-js/issues/1271(步骤 2)
参考:https : //github.com/bevacqua/dragula /issues/602(第 3 步)


Rus*_*dhu 5

最后我通过以下步骤解决了这个问题:

步骤1 :

npm install --save-dev @types/node

第2步 :

使用参考: https: //github.com/aws/aws-sdk-js/issues/1271(步骤2)

步骤3:

使用参考: https: //github.com/bevacqua/dragula/issues/602(第3步)

public uploadFileToAws(file, folderName, newFileName) {

    var aws_cognito_identity_pool_id = environment.pool_id;
    var aws_cognito_region = environment.aws_cognito_region;
    var aws_project_region = environment.aws_project_region;
    AWS.config.region = aws_project_region;
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: aws_cognito_identity_pool_id
    }, {
        region: aws_cognito_region
      });
    AWS.config.update({ customUserAgent: 'MobileHub v0.1' });

    const s3 = new S3({
      apiVersion: '2006-03-01',
      params: { Bucket: environment.bucket }
    });

    s3.upload({
        Key: folderName+'/'+newFileName,
        Bucket: environment.bucket,
        Body: file,
        ACL: 'private'
      },function (err, data) {
        this.fileuploading = false;
        if (err) {
          console.log(err, 'there was an error uploading your file');
        } else {
          console.log(data.Key+ ' uploaded successfully');          
        }        
        return true;
      });
  }
Run Code Online (Sandbox Code Playgroud)