英文:
How can I post multipart image without to save on disk?
问题
我需要下载一张图片并将其上传到另一个服务上。是否可以在不保存到磁盘的情况下上传?我查看了go文档,但没有找到任何直接的方法,甚至没有找到从磁盘上传/提交多部分的方法。
到目前为止,我有以下不工作的代码:
func upf(file []byte) (url string, err error) {
URL := "http:///max.com/upimg"
b := bytes.Buffer{}
writer := multipart.NewWriter(&b)
part, err := writer.CreateFormField(file)
if err != nil {
return "", err
}
err = writer.Close()
if err != nil {
return "", err
}
return http.NewRequest("POST", URL, &b)
}
英文:
I need to download an image and upload it on another service. Is it possible to upload it without to save it on disk ? I checked the go docs but I couldn't find any straightforward method not even to upload/post multi part from disk.
So far I have this non-working code
func upf(file []byte) (url string, err error) {
URL := "http:///max.com/upimg"
b := bytes.Buffer
writer := multipart.NewWriter(b)
part, err := writer.CreateFormField(file)
if err != nil {
return nil, err
}
err = writer.Close()
if err != nil {
return nil, err
}
return http.NewRequest("POST", URL, b)
}
答案1
得分: 4
回答如下:
response, error := http.Get("http://another.service.com/image.jpg")
if error != nil {
// 处理错误
}
_, error = http.Post("http://max.com/upimg", "image/jpg", response.Body)
if error != nil {
// 处理错误
}
如果需要进行多部分(multipart)的POST请求,你需要对响应的Body进行编码:
buffer := bytes.NewBuffer(nil)
encoder := multipart.NewWriter(buffer)
field, error := encoder.CreateFormField("image") // 将"image"设置为正确的字段名
if error != nil {
// 处理错误
}
_, error = io.Copy(field, response.Body)
if error != nil {
// 处理错误
}
// 然后使用buffer而不是response.Body进行POST请求
在你的POST请求中,记得设置正确的Content-Type头部(例如,http.Post的第二个参数)为:
"multipart/form-data; boundary=" + encoder.Boundary()
英文:
response, error := http.Get("http://another.service.com/image.jpg")
if error != nil {
// handle error
}
_, error = http.Post("http://max.com/upimg", "image/jpg", response.Body)
if error != nil {
// handle error
}
If you need to post multipart you'll have to encode the response's Body;
buffer := bytes.NewBuffer(nil)
encoder := multipart.NewWriter(buffer)
field, error := encoder.CreateFormField("image") // Set "image" to correct field name
if error != nil {
// handle error
}
_, error = io.Copy(field, response.Body)
if error != nil {
// handle error
}
// and then Post buffer instead of response.Body
Remember to set the correct Content-Type
header in your POST request (e.g. http.Post's second argument) to something like:
"multipart/form-data; boundary=" + encoder.Boundary()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论