英文:
How do I download a file with a http request in go language
问题
我想使用Go语言的http包从URL下载文件,并将图像保存到磁盘上,以便稍后在我的网页上显示。我该如何做到这一点?
我需要这样做是因为我想从Instagram下载图片,并将它们保存到我的公共文件夹中,以便在我的网页上显示。
我在下面创建了一个答案,供其他人使用我编写的代码。
英文:
I want to download a file from an url in go lang using the go http package and save the image to disk for later display on my webpage. How do I do this?
I need to do this because I want to download images from instagram and save them to my public folder for display on my webpage.
I created an answer below for others to use the code I came up with.
答案1
得分: 15
经过一些研究,我得到了以下代码:
import (
"os"
"net/http"
"io"
)
func downloadFile(filepath string, url string) (err error) {
// 创建文件
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// 获取数据
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// 将数据写入文件
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
这段代码运行良好,但在生产环境中可能需要进行一些改进。
英文:
After some research I came up with this.
import (
"os"
"net/http"
"io"
)
func downloadFile(filepath string, url string) (err error) {
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
It works well but might need a bit of refinement for use in production.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论