golang http 上传文件记录
// 测试客户端上传文件
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
)
func main() {
//err := post()
err := postBigFile()
if err != nil {
fmt.Println(err)
}
}
func post() error {
//读文件
path := "F:\\test\\hello.html"
targetUrl := "http://localhost:9090/upload"
bodyBuf := new(bytes.Buffer)
bodyWriter := multipart.NewWriter(bodyBuf)
fileWriter, err := bodyWriter.CreateFormFile("userfile", path)
if err != nil {
fmt.Println("error writing to buffer")
return err
}
fh, err := os.Open(path)
if err != nil {
fmt.Println("error opening file")
return err
}
defer fh.Close()
//iocopy (大文件性能呢!)
_, err = io.Copy(fileWriter, fh)
if err != nil {
return err
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.WriteField("xxxx", "yyyy")
bodyWriter.WriteField("1111", "2222")
bodyWriter.Close()
resp, err := http.Post(targetUrl, contentType, bodyBuf)
if err != nil {
return err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(resp.Status)
fmt.Println(string(resp_body))
return nil
}
func postBigFile() error {
//读文件
path := "F:\\test\\hello.html"
targetUrl := "http://localhost:9090/upload"
bodyBuf := bytes.NewBufferString("")
bodyWriter := multipart.NewWriter(bodyBuf)
_, err := bodyWriter.CreateFormFile("userfile", path)
if err != nil {
fmt.Println("error writing to buffer")
return err
}
file, err := os.Open(path)
if err != nil {
fmt.Println("error opening file")
return err
}
defer file.Close()
//大文件使用这个!!!
boundary := bodyWriter.Boundary()
closeString := fmt.Sprintf("\r\n--%s--\r\n", boundary)
closeBuf := bytes.NewBufferString(closeString)
rn := bytes.NewBufferString("\r\n")
bodyBufField := new(bytes.Buffer)
filedWrite := multipart.NewWriter(bodyBufField)
filedWrite.SetBoundary(boundary)
filedWrite.WriteField("xxxx", "yyyyyyyyyyy")
requestReader := io.MultiReader(bodyBuf, file, rn, bodyBufField, closeBuf)
contentType := bodyWriter.FormDataContentType()
resp, err := http.Post(targetUrl, contentType, requestReader)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(respBody))
if err != nil {
return err
}
return nil
}