直接贴代码吧。
服务端:
package main import ( "fmt" "io" "io/ioutil" "net/http" ) func main() { http.HandleFunc("/upload", upload) http.ListenAndServe(":8080", nil) } func upload(w http.ResponseWriter, r *http.Request) { reader, err := r.MultipartReader() if err != nil { fmt.Fprintln(w, err) return } for { part, err := reader.NextPart() if err == io.EOF { break } if err != nil { fmt.Fprintf(w, "unexpected error: %s\n", err) break } data, err := ioutil.ReadAll(part) if err != nil { fmt.Fprintln(w, err) continue } fmt.Printf("FormName(%s),FileName(%s)=>%s\n", part.FormName(), part.FileName(), string(data)) } }
客户端:
package main import ( "bytes" "fmt" "io/ioutil" "mime/multipart" "net/http" ) func main() { var buff bytes.Buffer writer := multipart.NewWriter(&buff) writer.WriteField("field", "this is a field") w, _ := writer.CreateFormFile("file", "test.txt") w.Write([]byte("this is a file")) writer.Close() var client http.Client resp, err := client.Post("http://127.0.0.1:8080/upload", writer.FormDataContentType(), &buff) if err != nil { fmt.Println(err) return } defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) }
有疑问加站长微信联系(非本文作者)