【发布时间】:2017-06-01 02:07:06
【问题描述】:
我想用golang post请求,上传图片,但是我不想传filepath,只想传[]字节 下面的文章不是我需要的,因为它们使用的是 os.Open golang POST data using the Content-Type multipart/form-data
func Upload(url, file string) (err error) {
// Prepare a form that you will submit to that URL.
var b bytes.Buffer
w := multipart.NewWriter(&b)
// Add your image file
f, err := os.Open(file)
if err != nil {
return
}
defer f.Close()
fw, err := w.CreateFormFile("image", file)
if err != nil {
return
}
if _, err = io.Copy(fw, f); err != nil {
return
}
// Add the other fields
if fw, err = w.CreateFormField("key"); err != nil {
return
}
if _, err = fw.Write([]byte("KEY")); err != nil {
return
}
// Don't forget to close the multipart writer.
// If you don't close it, your request will be missing the terminating boundary.
w.Close()
// Now that you have a form, you can submit it to your handler.
req, err := http.NewRequest("POST", url, &b)
if err != nil {
return
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
// Submit the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return
}
// Check the response
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("bad status: %s", res.Status)
}
return
}
【问题讨论】:
-
http.request.Body() 是字节流,可能你的问题属于客户端,这些图片是从哪里来的?是网站还是其他客户?
-
我的请求是这样的,前端和api(api1)是分开的,前端要传递一个base64的参数,在api(api1)中:这个参数会被转换成[]字节,然后通过http post调用另一个api(api2)
-
这里是我要求的参数 --8D4A8ED669208A7 Content-Disposition:form-data;name="charset" Content-Type:text/plain utf-8 --8D4A8ED669208A7 Content-Disposition:form-data ;名称= “符号” 内容类型:文本/无格式Qlv1mjWGUEq + 7i2FhTGjCa7WwFcZBHlg019JrHgjNJ2D98bEnkHKI9A + SCHM + xaewgaqC2i73lybrRNwzUpKJFlUoVcrnFhuMWbHCI73Zkg + mn8lLJrzMgoqPBTsMxze + 0uDCci7cmpM8ijTMKaxtwWddg910EzDMkQra14TiU4 = --8D4A8ED669208A7内容处置:形状数据;名称= “image_content”;文件名= “123.jpg” 内容-类型:图像/JPEG
-
我希望这样:if _, err = io.Copy(fw, []byte);错误!=零{返回}
-
答案已经在示例代码中,即不用
io.Copy(fw, f),直接用fw.Write(your-data)写。