Save an image from url to file

后端 未结 3 1524
猫巷女王i
猫巷女王i 2020-12-28 15:07

Very new to Go (first simple project I\'m working on).

Question: How do I get an image from URL and then save it to my computer?

Here\'s what I have so far:<

3条回答
  •  星月不相逢
    2020-12-28 15:39

    package main
    
    import (
        "io"
        "net/http"
        "os"
        "fmt"
    )
    
    func main() {
        img, _ := os.Create("image.jpg")
        defer img.Close()
    
        resp, _ := http.Get("http://i.imgur.com/Dz2r9lk.jpg")
        defer resp.Body.Close()
    
        b, _ := io.Copy(img, resp.Body)
        fmt.Println("File size: ", b)
    }
    

提交回复
热议问题