duanbi3151 2018-07-31 09:30
浏览 173
已采纳

如何将文件保留在内存中-在服务器之间传输文件而不将其存储在本地

I am in the process of writing a simple deployment tool which needs to take tar files from s3, extract them and then upload them to our staging server. I would like to do this without storing the files locally, keeping them in memory.

Here is my code to download files from s3

func s3downloadFile(downloader *s3manager.Downloader, item string) {
    localitem := strings.Replace(item, s3base, "", -1)
    os.MkdirAll(path.Dir(localitem), os.ModePerm)
    file, err := os.Create(localitem)
    if err != nil {
        exitErrorf("Unable to open file %q, %v", err)
    }

    defer file.Close()

    numBytes, err := downloader.Download(file,
        &s3.GetObjectInput{
            Bucket: aws.String(s3bucket),
            Key:    aws.String(item),
        })
    if err != nil {
        exitErrorf("Unable to download item %q, %v", item, err)
    }

    fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}

I would like to avoid having to create the directories and files in this example and just keep everything in memory. I left out the step that extracts the files from my code. The next step would be to upload the files with go-scp like so:

// Finaly, copy the file over
// Usage: CopyFile(fileReader, remotePath, permission)

client.CopyFile(f, "/path/to/remote/file", "0655")

My question would then focus on the file, err := os.Create(localitem) part of this code, how can I keep a filereader in memory instead of storing the file locally.

  • 写回答

1条回答 默认 最新

  • doujian7132 2018-07-31 10:27
    关注

    This is mentioned in the docs for Download:

    The w io.WriterAt can be satisfied by an os.File to do multipart concurrent downloads, or in memory []byte wrapper using aws.WriteAtBuffer.

    So use an aws.WriteAtBuffer instead of an *os.File:

    buf := new(aws.WriteAtBuffer)
    
    numBytes, err := downloader.Download(buf, &s3.GetObjectInput{
        Bucket: aws.String(s3bucket),
        Key:    aws.String(item),
    })
    
    tr := tar.NewReader(bytes.NewReader(buf.Bytes()))
    // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历