doumu6941 2015-07-31 20:25
浏览 73
已采纳

Golang GAE将图片网址保存到Blobstore

I am looking to save an image in Go, something like this:

url := "http://i.imgur.com/m1UIjW1.jpg"

response, e := http.Get(url)
if e != nil {
    log.Fatal(e)
}

defer response.Body.Close()

file, err := os.Create("/tmp/asdf.jpg")
if err != nil {
    log.Fatal(err)
}

_, err = io.Copy(file, response.Body)
if err != nil {
    log.Fatal(err)
}

file.Close()

However - I am using Blobstore on GAE and all of the examples I find seem to be based on some multi-part form upload based on a users browser...

How do I download an image on GAE/Blobstore with a simple GET request:

func handler(w http.ResponseWriter, r *http.Request) {
    urlImage := "http://i.imgur.com/m1UIjW1.jpg"
    //when a user calls this root handle, download urlImage to Blobstore
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
  • 写回答

1条回答 默认 最新

  • dqoeghe9452 2015-07-31 22:33
    关注

    I think, from context, that you mean "upload an image to blobstore" where you say "download an image on blobstore".

    Once upon a time you would have created a blobstore Writer with https://cloud.google.com/appengine/docs/go/blobstore/reference#Create , then written on it, and closed it. But as the docs mention this is now deprecated; nowadays, you use instead the package cloud/storage as in the example at https://godoc.org/google.golang.org/cloud/storage#example-NewWriter:

    wc := storage.NewWriter(ctx, "bucketname", "filename1")
    wc.ContentType = "image/jpg"
    wc.ACL = []storage.ACLRule{{storage.AllUsers, storage.RoleReader}}
    if _, err := wc.Write(response.Body); err != nil {
        log.Fatal(err)
    }
    

    etc, etc -- compared to the example, I've only changed the content type and exactly what bytes you write.

    Essentially, blobstore has been replaced by cloud storage, and you should use the latter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?