dougong2005 2017-01-22 09:30
浏览 59
已采纳

Golang将文件从URL保存到AppEngine中的GCS存储桶

I'm trying to get a image file from URL and save it to GCS storage using the documentation here.

I can't figure out how to create the file from response.Body to GSC given my AppEngine environment... I can't create using os.Create and reference a file path in this environment, right?

  • Looking for tips on passing the response.Body to the wc.Write() method while deployed in AppEngine.

Code to get file:

func main() {
    url := "http://i.imgur.com/m1UIjW1.jpg"
    // don't worry about errors
    response, e := http.Get(url)
    if e != nil {
        log.Fatal(e)
    }

    defer response.Body.Close()

    //open a file for writing
    file, err := os.Create("/tmp/asdf.jpg")
    if err != nil {
        log.Fatal(err)
    }
    // Use io.Copy to just dump the response body to the file. This supports huge files
    _, err = io.Copy(file, response.Body)
    if err != nil {
        log.Fatal(err)
    }
    file.Close()
    fmt.Println("Success!")
} 

Save a local file to GCS

func (d *demo) createFile(fileName string) {
        fmt.Fprintf(d.w, "Creating file /%v/%v
", d.bucketName, fileName)

        wc := d.bucket.Object(fileName).NewWriter(d.ctx)
        wc.ContentType = "text/plain"
        wc.Metadata = map[string]string{
                "x-goog-meta-foo": "foo",
                "x-goog-meta-bar": "bar",
        }
        d.cleanUp = append(d.cleanUp, fileName)

        if _, err := wc.Write([]byte("abcde
")); err != nil {
                d.errorf("createFile: unable to write data to bucket %q, file %q: %v", d.bucketName, fileName, err)
                return
        }
        if _, err := wc.Write([]byte(strings.Repeat("f", 1024*4) + "
")); err != nil {
                d.errorf("createFile: unable to write data to bucket %q, file %q: %v", d.bucketName, fileName, err)
                return
        }
        if err := wc.Close(); err != nil {
                d.errorf("createFile: unable to close bucket %q, file %q: %v", d.bucketName, fileName, err)
                return
        }
}

展开全部

  • 写回答

1条回答 默认 最新

  • douxu2081 2017-01-26 22:34
    关注

    It seems like you are looking for a Writer and a bytes.Buffer:

    var buff bytes.Buffer
    writer := NewWriter(buff)
    n, err := io.Copy(writer, response.Body)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 KeiI中头文件找不到怎么解决
  • ¥15 QT6将音频采样数据转PCM
  • ¥15 本地安装org.Hs.eg.dby一直这样的图片报错如何解决?
  • ¥15 下面三个文件分别是OFDM波形的数据,我的思路公式和我写的成像算法代码,有没有人能帮我改一改,如何解决?
  • ¥15 Ubuntu打开gazebo模型调不出来,如何解决?
  • ¥100 有chang请一位会arm和dsp的朋友解读一个工程
  • ¥50 求代做一个阿里云百炼的小实验
  • ¥15 查询优化:A表100000行,B表2000 行,内存页大小只有20页,运行时3页,设计两个表等值连接的最简单的算法
  • ¥15 led数码显示控制(标签-流程图)
  • ¥20 为什么在复位后出现错误帧
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部