【问题标题】:How to upload file in AWS S3 from Angular 8如何从 Angular 8 在 AWS S3 中上传文件
【发布时间】:2020-01-02 14:22:15
【问题描述】:

我在从 Angular 8 项目上传文件到 S3 时遇到错误。我已经按照下面的教程做所需的事情

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

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

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

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

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

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

【问题讨论】:

标签: angular amazon-s3 angular8


【解决方案1】:

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

  1. 安装依赖

    npm install --save-dev @types/node

  2. 需要在tsconfig.app.json中添加"types": ["node"]

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

    if (typeof (window as any).global === 'undefined') { (window as any).global = window; }
    

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

【讨论】:

    【解决方案2】:

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

    第一步:

    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;
          });
      }
    

    【讨论】:

    • 我在 Andriod 中运行应用程序时无法加载运行时编译器
    【解决方案3】:

    TypeScript 抱怨,因为需要一些节点环境类型。这是目前的一个限制,我们将来可以通过存根这些接口来解决这个问题。

    您可以尝试安装环境类型以查看它是否可以解决您的问题?

    npm install --save-dev @types/node
    

    【讨论】:

    • 我已经安装了上面的 npm 包,但我仍然面临同样的问题。
    【解决方案4】:
      uploadfile(file: FileList) {
    
        const files = file.item(0);
        this.uploadService.validateandUploadFile(files, 300, 300);
        setTimeout(() => {
    
          this.uploadService.getFile().subscribe((resData) => {
            // this.CommonService.hideSppiner();
            if (resData.data == "") {
              this.toastrService.successErrMsg(resData.message);
            } else {
              this.toastrService.successMsg("Success", resData.message);
            }
            this.chatBubbleForm.controls['avatarImage'].setValue(resData.data, { emitModelToViewChange: false });
            this.imageUrl = this.chatBubbleForm.controls['avatarImage'].value;
          });
    
        }, 8000);
      }
    

    service.ts

    import { Injectable } from '@angular/core';
        
        import * as AWS from 'aws-sdk/global';
        import * as S3 from 'aws-sdk/clients/s3';
        import { BehaviorSubject } from 'rxjs';
        
        
        @Injectable({
            providedIn: 'root'
        })
        export class UploadFileService {
        
        
            FOLDER = '/';
        
            imageUrl = "";
        
            resData: BehaviorSubject<any> = new BehaviorSubject(null);
        
            data = { message: "", data: "" };
        
            constructor() { }
            validateandUploadFile(file, Iheight, Iwidth) {
        
                let fileToUpload = file;
                if (fileToUpload.type == "image/jpeg" || fileToUpload.type == "image/png" || fileToUpload.type == "image/jpeg") {
                    //Show image preview
                    let reader = new FileReader();
                    reader.onload = (event: any) => {
                        var img = new Image();
                        img.onload = () => {
                            let width = img.width;
        
                            let height = img.height;
                            if (width <= Iwidth && height <= Iheight) {
                                this.imageUrl = event.target.result;
        
                                this.uploadfile(file);
                            } else {
        
                                this.data.message = "You can maximum upload " + Iheight + " * " + Iwidth + " File";
                                this.data.data = "";
                                this.resData.next(this.data);
                                return this.resData;
                            }
                        };
        
                        img.src = event.target.result;
                    }
                    reader.readAsDataURL(fileToUpload);
                } else {
                    this.data.message = "You can't be able to upload file except JPG and PNG format";
                    this.data.data = "";
                    this.resData.next(this.data);
                    return this.resData;
                }
            }
        
        
            uploadfile(file) {
        
                if (file != null) {
                    const bucket = new S3(
                        {
                            accessKeyId: '***************',
                            secretAccessKey: '***************************',
                            region: 'us-east-2'
                        }
                    );
                    const params = {
                        Bucket: '*************',
                        Key: file.name,
                        Body: file,
                        ACL: 'public-read'
        
                    };
                    var that = this;
        
                    bucket.upload(params, function (err, data) {
        
                        if (err) {
                            console.log('There was an error uploading your file: ', err);
                            return false;
                        }
        
        
                        console.log('Successfully uploaded file.', data);
                        that.data.message = "Successfully uploaded file.";
                        that.data.data = data.Location;
                        that.resData.next(that.data);
                        return that.resData;
                    });
        
                }
        
            }
            deleteFile(fileName) {
        
                const bucket = new S3(
                    {
                        accessKeyId: '*****************',
                        secretAccessKey: '*********************',
                        region: 'us-east-2'
                    }
                );
                var params = {
                    Bucket: '***************',
                    Key: fileName
                    /* 
                       where value for 'Key' equals 'pathName1/pathName2/.../pathNameN/fileName.ext'
                       - full path name to your file without '/' at the beginning
                    */
                };
                var that = this;
                bucket.deleteObject(params, function (err, data) {
                    if (err) console.log(err, err.stack); // an error occurred
                    else console.log(data)
        
                });
            }
            public getFile() {
                return this.resData.asObservable();
            }
        
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2019-09-21
      • 2020-05-26
      • 1970-01-01
      • 2019-12-18
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多