2019独角兽企业重金招聘Python工程师标准>>>
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)
}