<pre><code>
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/cheggaaa/pb"
)
func uploadFile(fileName string, targetURL string) (err error) {
buf := &bytes.Buffer{}
bodyMultiWriter := multipart.NewWriter(buf)
fileWriter, err := bodyMultiWriter.CreateFormFile("uploadFile", fileName)
if err != nil {
fmt.Println("writing to buf error.")
return err
}
hFile, err := os.Open(fileName)
if err != nil {
fmt.Println("opening file error.")
return err
}
//获取文件的大小
fileInfo, errFileInfo := os.Stat(fileName)
if errFileInfo != nil {
fmt.Println("file_info size error.")
return errFileInfo
}
//显示进度条
bar := pb.New(int(fileInfo.Size())).SetUnits(pb.U_BYTES).SetRefreshRate(time.Millisecond * 10)
bar.Start()
bar.ShowSpeed = true
bar.ShowFinalTime = true
bar.SetMaxWidth(80)
writer := io.MultiWriter(fileWriter, bar)
_, err = io.Copy(writer, hFile)
if err != nil {
return err
}
bar.Finish() //关闭进度条
contentType := bodyMultiWriter.FormDataContentType()
bodyMultiWriter.Close()
resp, err := http.Post(targetURL, contentType, buf)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return nil
}
func main() {
targetURL := "http://127.0.0.1:9090/upload"
fileName := `TEST.exe`
err := uploadFile(fileName, targetURL)
if err != nil {
fmt.Println("upload error.")
os.Exit(1)
}
var stop string
fmt.Scanln(&stop)
}
</code></pre>
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)