Go 下载网络图片或文件

臭大佬 2021-09-17 09:30:36 2136
Go 
简介 Go 下载网络图片或文件

代码


package main

import (
    "bufio"
    "fmt"
    "io"
    "net/http"
    "os"
    "path"
)

func main() {
    imgPath := "D:\\static\\uploadfile\\"
    imgUrl := "https://fanqie.ihuizong.cn/shopUuid_/fc616d29-a6e3-49a2-9045-3720c1770368.mp4"

    fileName := pathPack.Base(imgUrl)
    res, err := http.Get(imgUrl)
    if err != nil {
        fmt.Println("A error occurred!")
        return
    }
    defer res.Body.Close()
    // 获得get请求响应的reader对象
    reader := bufio.NewReaderSize(res.Body, 32*1024)
    file, err := os.Create(imgPath + fileName)
    if err != nil {
        panic(err)
    }
    // 获得文件的writer对象
    writer := bufio.NewWriter(file)
    written, _ := io.Copy(writer, reader)
    fmt.Printf("Total length: %d", written)
}