前端上传文件到Aws S3文件服务器

1、创建Identify Pool获取AWS凭证(根用户)

https://console.aws.amazon.com/cognito

 

2、设置CORS

由于SDK通过Ajax提交数据,需要在S3桶策略中配置跨域提交的CORS,示例中的*建议在生产环境中改成自己的域名.

<?xml version="1.0" encoding="UTF-8"?>

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">

<CORSRule>

    <AllowedOrigin>*</AllowedOrigin>

    <AllowedMethod>PUT</AllowedMethod>

    <AllowedMethod>POST</AllowedMethod>

    <AllowedMethod>DELETE</AllowedMethod>

    <AllowedMethod>GET</AllowedMethod>

    <AllowedMethod>HEAD</AllowedMethod>

    <MaxAgeSeconds>3000</MaxAgeSeconds>

    <AllowedHeader>*</AllowedHeader>

</CORSRule>

</CORSConfiguration>

3、设置存储桶策略,允许访问及上传
 
生成策略
 
ps:actions 选择getObject和putObject
 
设置策略
 
 
 

4、上传

npm install aws-sdk

let AWS = require('aws-sdk')

AWS.config.region = S3Region;

AWS.config.credentials = new AWS.CognitoIdentityCredentials({

 IdentityPoolId: S3IdentityPoolId,

})

AWS.config.credentials.get(function() {

      let accessKeyId = AWS.config.credentials.accessKeyId

      let secretAccessKey = AWS.config.credentials.secretAccessKey

      let sessionToken = AWS.config.credentials.sessionToken

      let s3 = new AWS.S3({

        'apiVersion': '2006-03-01',

        'accessKeyId': accessKeyId,

        'secretAccessKey': secretAccessKey,

        'sessionToken': sessionToken,

        'region_name': S3Region,

      })

      let data = {

        Bucket: Bucket,

        Key: objectkey,

        Body: file,

        ContentEncoding: 'base64',

        ContentType: 'image/jpeg',

      }

      s3.putObject(data, (err, data) => {})

}

 

posted @ 2020-07-27 16:13  似是故人来~  阅读(5110)  评论(0编辑  收藏  举报