下载网络图片
下载网络图片
package main
import "net/http"
func downloadImg(imgUrl string) (string, error){
res, err := http.Get(imgUrl)
if err != nil {
return "获取图片失败", err
}
defer res.Body.Close()
reader := bufio.NewReaderSize(res.Body, 32 * 1024)
//创建目录
downloadDir := "/home/wwwroot/psoriasis/"
imgPath := "statics/download/avatar/" + time.Now().Format("2006/01/")+"/"
err = os.MkdirAll( downloadDir+imgPath , 777)
if err != nil {
return "没有权限创建目录" , err
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
code := fmt.Sprintf("%06v", rnd.Int31n(1000000))
fileName := time.Now().Format("20060102150405") + code + ".png"
filePath := downloadDir + imgPath
file, err := os.Create(filePath + fileName)
if err != nil {
return "保存文件失败" , err
}
// 获得文件的writer对象
writer := bufio.NewWriter(file)
_, _ = io.Copy(writer, reader)
return imgPath + fileName, nil
}