簡體   English   中英

Angular 4/5文件上傳或圖像上傳到Amazon S3

[英]Angular 4/5 file upload or image upload to Amazon S3

我正在嘗試在我的MEAN應用程序中實現文件上傳。 我的后端(Node和Express)和前端(Angular)是分開部署的。 我需要的是通過Angular將文件上傳到amazon s3,成功上傳后獲取地址目的地然后將文件目的地保存到變量。

有沒有簡單的方法來實現這個? 假設我有一個這樣的表格

<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>

然后這個代碼將在我的組件上(僅用於測試我可以獲取文件)

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

在此輸入圖像描述

如何將文件從我的表單發送到Amazon S3? 然后在亞馬遜s3中獲取文件目的地,這樣我就可以將它保存到我的數據庫中以便稍后獲取它。 我也不確定我是否應該在我的后端或前端創建亞馬遜s3配置,我現在很困惑。

如果可以,請盡量避免在瀏覽器中使用AWS SDK,因為您無法對使用率進行評級。 或者更糟糕的是,如果您在前端存儲訪問密鑰,則可以公開您的AWS憑據。

相反,在node.js后端使用AWS SDK並將API公開為代理。 請參閱https://aws.amazon.com/sdk-for-node-js/

您應該使用AWS SDK for JavaScript。

您可以在此處查看上傳照片的示例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM