代码
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
func DownloadFile(url, targetDir, customFileName string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("GET request failed with status: %d", resp.StatusCode)
}
// 确保目标目录存在
err = os.MkdirAll(targetDir, os.ModePerm)
if err != nil {
return err
}
// 使用自定义的文件名
// filePath := filepath.Join(targetDir, filepath.Base(url))
filePath := filepath.Join(targetDir, customFileName)
// 创建文件
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
// 将远程文件内容写入本地文件
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
return nil
}
用法
Windows 下 实测 不需要目录存在,会自动创建
err := downloadFile("https://example.com/file.zip", "/path/to/download/directory", "myCustomFileName.zip")
if err != nil {
log.Fatal(err)
}
评论 (0)