【问题标题】:If I configure a s3 bucket for static website hosting, then can I upload assets to it through API?如果我为静态网站托管配置了一个 s3 存储桶,那么我可以通过 API 将资产上传到它吗?
【发布时间】:2020-04-24 00:29:48
【问题描述】:

我有一个为静态网站托管配置的 s3 存储桶,现在我经常需要更改我网站的资产, 我已经有一个自定义工具可以将资产上传到我的其他存储桶,是否可以通过 AWS API 将文件上传到我的 s3 存储桶?

【问题讨论】:

    标签: javascript node.js amazon-web-services amazon-s3 aws-sdk


    【解决方案1】:

    您可以使用 AWS-SDK 上传到 S3 存储桶。

    NPM 包:https://www.npmjs.com/package/aws-sdk

                // Load the AWS SDK for Node.js
                var AWS = require('aws-sdk');
                // Set the region 
                AWS.config.update({ region: 'REGION' });
    
                // Create S3 service object
                s3 = new AWS.S3({ apiVersion: '2006-03-01' });
    
                const s3 = new AWS.S3();
                const params = {
                    Bucket: S3_BUCKET, //bucket name
                    Key: `${s3Folder}/${filename}`, // type is not required
                    Body: base64, //image base64
                    ACL: 'public-read',
                    ContentEncoding: 'base64', // required
                    ContentType: `image/${fileType}` // required. Notice the back ticks
                }
    
                let location = '';
                let key = '';
                try {
                    const { Location, Key } = await s3.upload(params).promise();
                    location = Location;
                    key = Key;
                    console.log({ location, key })
                } catch (error) {
                    console.log("Error", error)
                }
    

    阅读更多@AWS 文档:https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html

    【讨论】:

    • 哦,好的,我会试试的,顺便说一句,我当前的自定义工具使用签名请求来上传文件,但这不起作用,我是否缺少设置,或者它不适用于为静态托管配置的存储桶? docs.aws.amazon.com/AmazonS3/latest/dev/…
    • 尝试将资产转储到另一个存储桶中,并将该存储桶中的资产用于您的静态网站。
    【解决方案2】:

    是的,这是一种完全可以接受的上传新资产的方式,而不是我的做法,但它应该可以正常工作,但最终无论您选择上传这些资产,它都有可能使用相同的 API 调用无论如何。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2020-04-05
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多