Angular 4/5 文件上传或图像上传到 Amazon S3

She*_*ito 5 amazon-s3 typescript angular

我正在尝试在我的 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>
Run Code Online (Sandbox Code Playgroud)

然后这段代码将在我的组件上(只是为了测试我可以获取文件)

@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);
} 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我如何将文件从我的表单发送到 Amazon S3?然后在 amazon s3 中获取文件目标,以便我可以将其保存到我的数据库中以供稍后获取。我也不确定是否应该为后端或前端创建 amazon s3 配置,我现在很困惑。

Tom*_*ula 2

您应该使用适用于 JavaScript 的 AWS 开发工具包。

您可以在此处查看上传照片的示例。

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);
  });
}
Run Code Online (Sandbox Code Playgroud)