繁体   English   中英

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

[英]How to upload file in AWS S3 from Angular 8

我在从 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;

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

在花了几个小时之后,我终于提出了解决方案。 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; }

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

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

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

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

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

npm install --save-dev @types/node
  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);
  }

服务.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();
        }
    
    }

暂无
暂无

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

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