Angular对接AWS S3接口上传文件样例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012760435/article/details/82876247

因为没有找到Angular版的接口,故在此使用了javascript版的。
首先要添加官方依赖

"aws-amplify": "^1.1.3",
"aws-amplify-angular": "^2.0.7",

然后组件中导入

import AWS from 'aws-sdk/lib/aws';

方法体

  doUpload(file: any): void {
    const formData = new FormData();
    formData.append('file', file);

    let accessKeyId: string;
    let secretAccessKey: string;
    this.keycloakService.loadUserProfile().then(res => {
      accessKeyId = res["attributes"]["accesskeyid"][0];
      secretAccessKey = res["attributes"]["secretaccesskey"][0];
    });

    let endPoint: string;
    this.inobjBucketUploadService.getBucketDomain(this.bucketName).subscribe(res => {
      endPoint = res.msg;
    });

	//连接配置在此完成
    AWS.config.update({
      region: this.region,
      credentials: {
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey
      },
      endpoint: endPoint
    });
    const params = {
      Bucket: this.bucketName,
      Key: file.name,
      Body: formData
    };

    let s3 = new AWS.S3();
    s3.upload(params, function (err, data) {
      console.log(err, data);
    });
  }

猜你喜欢

转载自blog.csdn.net/u012760435/article/details/82876247