下载文件的最简单方法是什么?

huangapple go评论98阅读模式
英文:

Easiest way to download a file?

问题

我可以做类似下面的事情,这会给我一个响应类,但我不确定如何将io.reader写入文件。最直接的方法是什么?

http.Get("https://www.domain.com/some.jpg")
英文:

I can do something like below, which gives me a response class, but I'm not exactly sure how to write the io.reader to a file. What is the most straightforward way?

http.Get("https://www.domain.com/some.jpg")

答案1

得分: 9

如果文件足够小,最简单的解决方案是使用ioutil.WriteFileioutil.ReadAll的组合:

resp, err := http.Get("your url")
bytes, err := ioutil.ReadAll(resp.Body)
err = ioutil.WriteFile(filename, bytes, 0666)

如果文件不太小,最好避免创建和填充bytes数组。然后你应该使用io.Copy,它只是将字节从读取器复制到写入器:

resp, err := http.Get("your url")
f, err := os.Create(filename)
defer f.Close()
_, err := io.Copy(f, resp.Body)

在这两种情况下,你必须添加相关的错误处理。

英文:

If the file is small enough the easiest solution is to use ioutil.WriteFile combined with ioutil.ReadAll :

resp, err := http.Get("your url")
bytes, err := ioutil.ReadAll(resp.Body)
err = ioutil.WriteFile(filename, bytes, 0666)

If your file isn't so small, you'd better avoid creating and filling the bytes array. Then you should use io.Copy which simply copies the bytes from the reader to the writer :

resp, err := http.Get("your url")
f, err := os.Create(filename)
defer f.Close()
_, err := io.Copy(f, resp.Body)

You must add the relevant error handling in both cases.

答案2

得分: 0

ReadFrom在某些情况下非常有用:

package main

import (
   "net/http"
   "os"
)

func main() {
   r, e := http.Get("http://speedtest.lax.hivelocity.net")
   if e != nil {
      panic(e)
   }
   defer r.Body.Close()
   f, e := os.Create("index.html")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   f.ReadFrom(r.Body)
}

https://golang.org/pkg/os#File.ReadFrom

英文:

ReadFrom is useful in some cases:

package main

import (
   "net/http"
   "os"
)

func main() {
   r, e := http.Get("http://speedtest.lax.hivelocity.net")
   if e != nil {
      panic(e)
   }
   defer r.Body.Close()
   f, e := os.Create("index.html")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   f.ReadFrom(r.Body)
}

https://golang.org/pkg/os#File.ReadFrom

huangapple
  • 本文由 发表于 2013年6月26日 02:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/17305277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定