前端上傳文件到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) => {})

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM