如何在Go中发送带有图片和某些参数的http发布请求?

I am trying to make an http post request with image and parameters in the form-data, but when I am adding image, my parameters are lost.

testProduct := &Product{
    Name: "TestProductName",
    ImageExtension: "png",
}

var b bytes.Buffer
multipartWriter := multipart.NewWriter(&b)
multipartWriter.CreateFormFile("image", "../test.png")
multipartWriter.Close()

form = url.Values{}
form.Add("name", testProduct.Name)
form.Add("image_extension", testProduct.ImageExtension)

req, _ := http.NewRequest(http.MethodPost, "api/v1/admin/products/", &b)

req.PostForm = form
req.Header.Add("Authorization", "Bearer "+loginResponse.Token)
req.Header.Set("Content-Type", multipartWriter.FormDataContentType())

recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)

But when the request handled the parameters doesn't bind: https://i.imgur.com/JmT4qLh.png

This is the product struct:

type Product struct {
    ID             string `form:"id" json:"id"`
    Name           string `form:"name" json:"name"`
    Price          int64  `form:"price" json:"price"`
    ImageExtension string `form:"image_extension" json:"image_extension"`
}
duancai7568
duancai7568 谢谢!
大约一年之前 回复
donglin317704291
donglin317704291 另请注意,http.Client会忽略*http.Request.PostForm,因此您切勿在客户端请求上设置PostForm。
大约一年之前 回复
dongqian6554
dongqian6554 使用multipartWriter.WriteField作为名称和image_extension,并删除=url.Values{}...形式的东西。
大约一年之前 回复

1个回答

    testProduct := &Product{
    Name:           "TestProductName",
    ImageExtension: "png",
}

pr, pw := io.Pipe()
form := multipart.NewWriter(pw)

go func() {
    defer pw.Close()

    err := form.WriteField("name", testProduct.Name)
    if err != nil {
        return
    }

    err = form.WriteField("image_extension", testProduct.ImageExtension)

    file, err := os.Open("a.png") // path to image file
    if err != nil {
        return
    }

    w, err := form.CreateFormFile("image", "sampleImageFileName.png")
    if err != nil {
        return
    }

    _, err = io.Copy(w, file)
    if err != nil {
        return
    }

    form.Close()
}()

r, err := http.NewRequest(http.MethodPost, "api/v1/admin/products/", pr)
if err != nil {
    return
}
r.Header.Set("Content-Type", form.FormDataContentType())
doutu4335
doutu4335 谢谢你,伙计
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐