共计 1000 个字符,预计需要花费 3 分钟才能阅读完成。
http 下载文件的实质就是在响应体中拿到响应数据并写入到文件的操作,第二种形式是实现了一个实时显示下载进度的性能
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func downloadFile(url, fileName string) {resp, err := http.Get(url)
if err != nil {panic(err)
}
defer func() {_ = resp.Body.Close()}()
file, err := os.Create(fileName)
if err != nil {panic(err)
}
defer file.Close()
n, err := io.Copy(file, resp.Body)
fmt.Println(n, err)
}
type Reader struct {
io.Reader
Total int64
Currnet int64
}
func (r *Reader) Read(p []byte) (n int, err error) {n, err = r.Reader.Read(p)
r.Currnet += int64(n)
fmt.Printf("\r %.2f%%", float64(r.Currnet * 10000 / r.Total) / 100)
return
}
func DownloadFileProgress(url, fileName string){resp, err := http.Get(url)
if err != nil {panic(err)
}
defer func() {_ = resp.Body.Close()}()
file, err := os.Create(fileName)
if err != nil {panic(err)
}
defer file.Close()
reader := &Reader{
Reader: resp.Body,
Total: resp.ContentLength,
}
io.Copy(file, reader)
}
func main(){
// 下载文件 url
url := "https://i1.hdslb.com/bfs/face/0d2f52b9e1dae83b2cd710b38ee911533db32774.jpg"
// 下载后保留的文件名
fileName := "example.png"
//downloadFile(url, fileName)
DownloadFileProgress(url, fileName)
}
正文完