Как загрузить файл в AWS S3 из Angular 8

Я столкнулся с ошибками при загрузке файлов на S3 из Angular 8 Project. Я следую приведенному ниже руководству и делаю необходимые вещи

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

Но я не могу использовать библиотеку S3 в служебном файле.

Скриншот ошибки

строки ниже генерируют ошибки, которые я думаю, но все еще не уверен, где что-то отсутствует

импортировать * как AWS из aws-sdk / global;

импортировать * как S3 из 'aws-sdk / clients / s3';

Есть ли кто-нибудь, кто может мне помочь избавиться от этого?


person Rushabh Madhu    schedule 02.01.2020    source источник
comment
Взгляните на эту проблему, похоже, она решает эту проблему: github.com/ aws / aws-sdk-js / issues / 1271   -  person pascalpuetz    schedule 02.01.2020


Ответы (4)


Я наконец пришел с решением, потратив на него пару часов. шаги решения приведены ниже для проекта Angular 8.

  1. Установить зависимость

    npm install --save-dev @ типы / узел

  2. Необходимо добавить «типы»: [«узел»] в 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)

person Rushabh Madhu    schedule 03.01.2020

Наконец, я решил проблему, выполнив следующие шаги:

Шаг 1 :

npm install --save-dev @ типы / узел

Шаг 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;
      });
  }
person Rushabh Madhu    schedule 07.02.2020
comment
Я получаю, что не удалось загрузить компилятор времени выполнения при запуске приложения в Andriod - person Naga; 11.06.2020

TypeScript жалуется, потому что необходимы некоторые типы среды узлов. На данный момент это ограничение, которое мы, возможно, сможем обойти, заглушив эти интерфейсы в будущем.

Можете ли вы попробовать установить типизацию среды, чтобы увидеть, решит ли она вашу проблему?

npm install --save-dev @types/node
person AWS PS    schedule 02.01.2020
comment
Я установил вышеуказанный пакет npm, но все еще сталкиваюсь с той же проблемой. - person Rushabh Madhu; 03.01.2020

  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();
        }
    
    }
person zeel    schedule 07.04.2021