首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象上载到AWS S3,而不使用aws go创建文件。

将对象上载到AWS S3,而不使用aws go创建文件。
EN

Stack Overflow用户
提问于 2017-12-03 18:34:04
回答 4查看 11.4K关注 0票数 4

我正在尝试使用golang将一个对象上传到AWS S3,而不需要在我的系统中创建一个文件(尝试只上传字符串)。但我很难做到这一点。有人能给我举一个例子,说明我如何在不需要创建文件的情况下上传到AWS S3?

关于如何上载文件的AWS示例:

代码语言:javascript
复制
// Creates a S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
//    go run s3_upload_object.go BUCKET_NAME FILENAME
func main() {
    if len(os.Args) != 3 {
        exitErrorf("bucket and file name required\nUsage: %s bucket_name filename",
            os.Args[0])
    }

    bucket := os.Args[1]
    filename := os.Args[2]

    file, err := os.Open(filename)
    if err != nil {
        exitErrorf("Unable to open file %q, %v", err)
    }

    defer file.Close()

    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager
    // for more information on configuring part size, and concurrency.
    //
    // http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader
    uploader := s3manager.NewUploader(sess)

    // Upload the file's body to S3 bucket as an object with the key being the
    // same as the filename.
    _, err = uploader.Upload(&s3manager.UploadInput{
        Bucket: aws.String(bucket),

        // Can also use the `filepath` standard library package to modify the
        // filename as need for an S3 object key. Such as turning absolute path
        // to a relative path.
        Key: aws.String(filename),

        // The file to be uploaded. io.ReadSeeker is preferred as the Uploader
        // will be able to optimize memory when uploading large content. io.Reader
        // is supported, but will require buffering of the reader's bytes for
        // each part.
        Body: file,
    })
    if err != nil {
        // Print the error and exit.
        exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err)
    }

    fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
}

我已经尝试以编程方式创建该文件,但它正在我的系统上创建文件,然后将其上传到S3。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-12-03 18:59:42

Body结构的UploadInput字段只是一个io.Reader。所以传递任何你想要的io.Reader --它不需要是一个文件。

票数 5
EN

Stack Overflow用户

发布于 2018-09-06 00:37:55

在这个答案中,我将张贴所有对我有用的与这个问题有关的东西。非常感谢@ThunderCat和@Flimzy提醒我上传请求的body参数已经是一个io.Reader。我将张贴一些示例代码,评论我从这个问题中学到了什么,以及它如何帮助我解决这个问题。也许这会帮助像我和@AlokKumarSingh这样的人。

案例1:您已经有了内存中的数据(例如,从诸如Kafka、Kinesis或SQS这样的流/消息传递服务接收数据)

代码语言:javascript
复制
func main() {
    if len(os.Args) != 3 {
        fmt.Printf(
            "bucket and file name required\nUsage: %s bucket_name filename",
            os.Args[0],
        )
    }

    bucket := os.Args[1]
    filename := os.Args[2]

    // this is your data that you have in memory
    // in this example it is hard coded but it may come from very distinct
    // sources, like streaming services for example.
    data := "Hello, world!"

    // create a reader from data data in memory
    reader := strings.NewReader(data)

    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1")},
    )
    uploader := s3manager.NewUploader(sess)

    _, err = uploader.Upload(&s3manager.UploadInput{
        Bucket: aws.String(bucket),
        Key: aws.String(filename),
        // here you pass your reader
        // the aws sdk will manage all the memory and file reading for you
        Body: reader,
    })
    if err != nil {.
        fmt.Printf("Unable to upload %q to %q, %v", filename, bucket, err)
    }

    fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
}

案例2:您已经有了一个持久化文件,并且希望上传它,但是您不想将整个文件保存在内存中:

代码语言:javascript
复制
func main() {
    if len(os.Args) != 3 {
        fmt.Printf(
            "bucket and file name required\nUsage: %s bucket_name filename",
            os.Args[0],
        )
    }

    bucket := os.Args[1]
    filename := os.Args[2]

    // open your file
    // the trick here is that the method os.Open just returns for you a reader
    // for the desired file, so you will not maintain the whole file in memory.
    // I know this might sound obvious, but for a starter (as I was at the time
    // of the question) it is not.
    fileReader, err := os.Open(filename)
    if err != nil {
        fmt.Printf("Unable to open file %q, %v", err)
    }
    defer fileReader.Close()

    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1")},
    )
    uploader := s3manager.NewUploader(sess)

    _, err = uploader.Upload(&s3manager.UploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(filename),
        // here you pass your reader
        // the aws sdk will manage all the memory and file reading for you
        Body: fileReader,
    })
    if err != nil {
        fmt.Printf("Unable to upload %q to %q, %v", filename, bucket, err)
    }

    fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
}

案例3:这是我在系统的最终版本上实现它的方式,但是要理解为什么要这样做,我必须给出一些背景。

我的用例进化了一点。上传代码将是Lambda中的一个函数,文件结果显示是巨大的。这意味着什么?如果我通过一个附加到Lambda函数的API网关中的入口点上传文件,我将不得不等待整个文件在Lambda中完成上传。因为lambda是根据调用的持续时间和内存使用情况来定价的,所以这可能是一个很大的问题。

因此,为了解决这个问题,我在上传时使用了一个预先签名的post URL。这对架构/工作流有何影响?

我不是从后端代码上传到S3,而是创建并验证一个URL,用于将对象发送到后端的S3,并将该URL发送到前端。有了它,我就实现了一个多部分上传到那个URL。我知道这比这个问题要具体得多,但要找到这个解决方案并不容易,所以我认为最好在这里为其他人记录一下。

下面是如何在nodejs中创建预签名URL的示例。

代码语言:javascript
复制
const AWS = require('aws-sdk');

module.exports.upload = async (event, context, callback) => {

  const s3 = new AWS.S3({ signatureVersion: 'v4' });
  const body = JSON.parse(event.body);

  const params = {
    Bucket: process.env.FILES_BUCKET_NAME,
    Fields: {
      key: body.filename,
    },
    Expires: 60 * 60
  }

  let promise = new Promise((resolve, reject) => {
    s3.createPresignedPost(params, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  })

  return await promise
    .then((data) => {
      return {
        statusCode: 200,
        body: JSON.stringify({
          message: 'Successfully created a pre-signed post url.',
          data: data,
        })
      }
    })
    .catch((err) => {
      return {
        statusCode: 400,
        body: JSON.stringify({
          message: 'An error occurred while trying to create a pre-signed post url',
          error: err,
        })
      }
    });
};

如果您想使用go --这是相同的想法,您只需更改de即可。

票数 8
EN

Stack Overflow用户

发布于 2020-04-21 01:14:52

下面是我编写的一个小实现,它利用管道并合并超时。

代码语言:javascript
复制
package example

import (
    "context"
    "fmt"
    "io"
    "sync"
    "time"

    "github.com/aws/aws-sdk-go/service/s3/s3manager"
)

func FileWriter(ctx context.Context, uploader *s3manager.Uploader, wg *sync.WaitGroup, bucket string, key string, timeout time.Duration) (writer *io.PipeWriter) {
    // create a per-file flush timeout
    fileCtx, cancel := context.WithTimeout(ctx, timeout)

    // pipes are open until one end is closed
    pr, pw := io.Pipe()

    wg.Add(1)
    go func() {
        params := &s3manager.UploadInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(key),
            Body:   pr,
        }

        // blocking
        _, err := uploader.Upload(params)
        if err != nil {
            fmt.Printf("Unable to upload, %v. Bucket: %s", err, bucket)
        }

        // always call context cancel functions!
        cancel()
        wg.Done()
    }()

    // when context is cancelled, close the pipe
    go func() {
        <-fileCtx.Done()
        // should check fileCtx.Err() here
        if err := pw.Close(); err != nil {
            fmt.Printf("Unable to close")
        }
    }()

    return pw
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47621804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档