首先是获取form-data内容
func ResendFormFile(r *http.Request, URL string) {
data := r.FormValue("data")
formFile, fileHeader, err := r.FormFile("pic")
if err != nil {
return
}
_, status := RequestPost(formFile, fileHeader.Filename, []byte(data), URL)
if (status / 100) != 2 {
fmt.Println("转发图片失败")
}
return
}
然后是发送
func RequestPost(formFile multipart.File, filename string, data []byte, postURL string) (resp interface{}, status int) {
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)
if fw, err := w.CreateFormField("data"); err == nil {
fw.Write(data)
}
if createFormFile, err := w.CreateFormFile("pic", filename); err == nil {
readAll, _ := ioutil.ReadAll(formFile)
createFormFile.Write(readAll)
}
w.Close()
req, err := http.NewRequest(http.MethodPost, postURL, buf)
if err != nil {
return
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return
}
return res.Body, res.StatusCode
}
这样返回的body是不可以直接json序列化的
可以先使用ioutil读出来或者byte.Buffer进行中转都是比较简单的选择
func UnmarshalWriter(body io.ReadCloser, w http.ResponseWriter) {
all, _ := ioutil.ReadAll(body)
buffer := bytes.NewBuffer(all)
buffer.WriteTo(w)
}
基本操作就这么多,欢迎提问!