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

时间:2017-01-22 17:30:13

标签: google-app-engine go

我尝试get a image file from URL并使用文档here将其保存到GCS存储空间。

在我的AppEngine环境下,我无法弄清楚如何从response.Body创建文件到GSC ...我无法使用os.Create创建并在此环境中引用文件路径,对吗?

  • 在AppEngine中部署时,查找有关将response.Body传递给wc.Write()方法的提示。

获取文件的代码:

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!")
} 

将本地文件保存到GCS

func (d *demo) createFile(fileName string) {
        fmt.Fprintf(d.w, "Creating file /%v/%v\n", 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\n")); 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) + "\n")); 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 个答案:

答案 0 :(得分:0)

您好像在寻找Writerbytes.Buffer

<meta http-equiv="Content-Security-Policy" content="default-src *; frame-src * ;">