gpt4 book ai didi

go - 如何在不保存在磁盘上的情况下发布多部分图像?

转载 作者:IT王子 更新时间:2023-10-29 02:30:23 25 4
gpt4 key购买 nike

我需要下载图片并将其上传到其他服务。是否可以上传而不将其保存在磁盘上?我检查了 go docs但我找不到任何直接的方法,甚至无法从磁盘上传/发布多部分。到目前为止,我有这个非工作代码

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

最佳答案

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
}

如果您需要发布多部分,则必须对响应的正文进行编码;

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

请记住在您的 POST 请求(例如 http.Post 的第二个参数)中设置正确的 Content-Type header :

"multipart/form-data; boundary=" + encoder.Boundary()

关于go - 如何在不保存在磁盘上的情况下发布多部分图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com