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

时间:2019-08-21 10:16:06

标签: image file http go post

我正在尝试在表单数据中发出包含图像和参数的http发布请求,但是当我添加图像时,我的参数丢失了。

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)

但是当请求处理后,参数不绑定: https://i.imgur.com/JmT4qLh.png

这是产品结构:

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"`
}

1 个答案:

答案 0 :(得分:0)

    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())