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)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)