Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4/5 file upload or image upload to Amazon S3

I'm trying to implement file upload in my MEAN app. My backend (Node and Express) and frontend (Angular) was deployed separately. What I need is to upload the file to amazon s3 through Angular, get the address destination after successful upload then save the file destination to a variable.

Is there any easy way to implement this? Let's say I have a form like this

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <input type="file" id="myImage" (change)="onFileChange($event)" #fileInput>
    <hr>

   <div class="text-right">
        <button type="submit" class="btn btn-primary">Actualizar perfil</button>
   </div><br>
</form>

Then this code would be on my component (just for testing that I can get the file)

@ViewChild('fileInput') fileInput: ElementRef;

createForm() {
    this.form = this.formBuilder.group({
        'myImage': null
    });
}


onFileChange(event) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length > 0) {
        let file = event.target.files[0];
        reader.readAsDataURL(file);
        reader.onload = () => {
        this.form.get('myImage').setValue({
                filename: file.name,
                filetype: file.type,
                value: reader.result.split(',')[1]
            })
        };
    }
}

onSubmit() {
    const formModel = this.form.value;
    this.loading    = true;

    setTimeout(() => {
        console.log(formModel);
        alert('Finished uploading');
        this.loading = false;
    }, 1000);
} 

enter image description here

How would I send the file from my form to Amazon S3? Then get the file destination in amazon s3 so I can save it to my database for fetching it later. I'm also not sure If should I create the amazon s3 configuration to my backend or frontend, I'm so confused right now.

like image 758
Sherwin Ablaña Dapito Avatar asked Apr 23 '18 10:04

Sherwin Ablaña Dapito


Video Answer


2 Answers

If you can, try to avoid using AWS SDK in the browser since you won't be able to rate limit the usage. Or worse you can expose your AWS credentials, if you store access key on the front-end.

Instead, use AWS SDK in your node.js backend and expose an API as a proxy. See https://aws.amazon.com/sdk-for-node-js/.

like image 175
Kelvin Lai Avatar answered Oct 21 '22 07:10

Kelvin Lai


You should use AWS SDK for JavaScript.

You can see the example of uploading the photo here.

function addPhoto(albumName) {
  var files = document.getElementById('photoupload').files;
  if (!files.length) {
    return alert('Please choose a file to upload first.');
  }
  var file = files[0];
  var fileName = file.name;
  var albumPhotosKey = encodeURIComponent(albumName) + '//';

  var photoKey = albumPhotosKey + fileName;
  s3.upload({
    Key: photoKey,
    Body: file,
    ACL: 'public-read'
  }, function(err, data) {
    if (err) {
      return alert('There was an error uploading your photo: ', err.message);
    }
    alert('Successfully uploaded photo.');
    viewAlbum(albumName);
  });
}
like image 2
Tomasz Kula Avatar answered Oct 21 '22 06:10

Tomasz Kula