package main import ( "bytes" "errors" "fmt" "io/IoUtil" "mime/multipart" "net/http" ) func main() { createMemoToAmazon() } func createMemoToAmazon() error { buf := new(bytes.Buffer) w := multipart.NewWriter(buf) err := w.WriteField("comment","我的世界!!!") if err != nil { fmt.Println(err) return err } resp,err := http.Get("http://www.xxx.com/1d595495-0580-49ec-b96c-cc3346096718") if err != nil { fmt.Println(err) return err } defer resp.Body.Close() if resp.StatusCode != 200 { return errors.New("resp status:" + fmt.Sprint(resp.StatusCode)) } bin,err := IoUtil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return err } fw,err := w.CreateFormFile("file","1d595495-0580-49ec-b96c-cc3346096718") if err != nil { fmt.Println(err) return err } _,err = fw.Write(bin) if err != nil { fmt.Println(err) return err } w.Close() req,err := http.NewRequest("POST","http://localhost:8080/info",buf) if err != nil { fmt.Println("req err: ",err) return err } req.Header.Set("Content-Type",w.FormDataContentType()) resp,err = http.DefaultClient.Do(req) if err != nil { fmt.Println("resp err: ",err) return err } defer resp.Body.Close() if resp.StatusCode != 200 { return errors.New("resp status:" + fmt.Sprint(resp.StatusCode)) } return nil }
如果要指定上传的每个部分的Content-Type,则需要重写multipart.Writer的CreateFormField和CreateFormFile方法
func CreateFormFile(fieldname,filename,contentType string,w *multipart.Writer) (io.Writer,error) { h := make(textproto.MIMEHeader) h.Set("Content-Disposition",fmt.Sprintf(`form-data; name="%s"; filename="%s"`,escapeQuotes(fieldname),escapeQuotes(filename))) h.Set("Content-Type",contentType) return w.CreatePart(h) }原文链接:https://www.f2er.com/go/190035.html