How to upload file in AWS S3 from Angular 8
Asked Answered
S

4

9

I am facing errors while uploading files to S3 from Angular 8 Project. I have follow below tutorial and do the required things

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

But I am not able to use S3 Library in service file.

Error Screenshot

below lines are generating errors that i think but still not sure where is missing things

import * as AWS from 'aws-sdk/global';

import * as S3 from 'aws-sdk/clients/s3';

Is there anyone who can help me to get rid out of it.

Springclean answered 2/1, 2020 at 14:22 Comment(1)
Take a look at this issue, it seems to adress this problem: github.com/aws/aws-sdk-js/issues/1271Zygoma
S
5

Finally I have solved the issue by below Steps:

Step 1 :

npm install --save-dev @types/node

Step 2 :

Use Reference : https://github.com/aws/aws-sdk-js/issues/1271 (Step 2)

Step 3 :

Use Reference : https://github.com/bevacqua/dragula/issues/602 (Step 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;
      });
  }
Springclean answered 7/2, 2020 at 8:29 Comment(1)
I am getting could not load runtime compiler while running the App in AndriodAgueweed
S
6

I finally come with solution after spending couple of hours on it. solutions steps are as below for Angular 8 Project.

  1. Install dependancy

    npm install --save-dev @types/node

  2. Need to add "types": ["node"] to the tsconfig.app.json

  3. Add below lines in polyfills.js

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

Reference : Last answer by @AWS PS (Step 1)
Reference : https://github.com/aws/aws-sdk-js/issues/1271 (Step 2)
Reference : https://github.com/bevacqua/dragula/issues/602 (Step 3)

Springclean answered 3/1, 2020 at 11:27 Comment(0)
S
5

Finally I have solved the issue by below Steps:

Step 1 :

npm install --save-dev @types/node

Step 2 :

Use Reference : https://github.com/aws/aws-sdk-js/issues/1271 (Step 2)

Step 3 :

Use Reference : https://github.com/bevacqua/dragula/issues/602 (Step 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;
      });
  }
Springclean answered 7/2, 2020 at 8:29 Comment(1)
I am getting could not load runtime compiler while running the App in AndriodAgueweed
D
0

TypeScript is complaining because some node environment types are needed. This is a limitation for now that we might be able to get around by stubbing those interfaces in the future.

can you try installing the environment typings to see if it gets around your issue?

npm install --save-dev @types/node
Dinnerware answered 2/1, 2020 at 14:56 Comment(1)
I have install the above npm package but still I am facing the same issue.Springclean
Z
0
  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();
        }
    
    }
Zins answered 7/4, 2021 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.