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

huangapple go评论76阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年5月9日 17:42:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/23561379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定