From 2cdbba56a4111b87c1159125de7f0447387db824 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Tue, 18 Apr 2023 20:09:56 +0800 Subject: [PATCH] feat: add UploadFile and DownloadFile --- netutil/net.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/netutil/net.go b/netutil/net.go index ab4dab2..6111fd6 100644 --- a/netutil/net.go +++ b/netutil/net.go @@ -1,12 +1,18 @@ package netutil import ( + "bytes" "encoding/json" + "errors" "io" + "mime/multipart" "net" "net/http" "net/url" + "os" "strings" + + "github.com/duke-git/lancet/v2/fileutil" ) // GetInternalIp return internal ipv4. @@ -178,3 +184,64 @@ func EncodeUrl(urlStr string) (string, error) { return URL.String(), nil } + +// DownloadFile will upload the file to a server. +func UploadFile(filepath string, server string) (bool, error) { + if !fileutil.IsExist(filepath) { + return false, errors.New("file not exist") + } + + fileInfo, err := os.Stat(filepath) + if err != nil { + return false, err + } + + bodyBuffer := &bytes.Buffer{} + writer := multipart.NewWriter(bodyBuffer) + + formFile, err := writer.CreateFormFile("uploadfile", fileInfo.Name()) + if err != nil { + return false, err + } + + srcFile, err := os.Open(filepath) + if err != nil { + return false, err + } + defer srcFile.Close() + + _, err = io.Copy(formFile, srcFile) + if err != nil { + return false, err + } + + contentType := writer.FormDataContentType() + writer.Close() + + _, err = http.Post(server, contentType, bodyBuffer) + if err != nil { + return false, err + } + + return true, nil +} + +// DownloadFile will download the file exist in url to a local file. +// Play: todo +func DownloadFile(filepath string, url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + defer resp.Body.Close() + + out, err := os.Create(filepath) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, resp.Body) + + return err +}