如何将图像写入请求体中

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

how to write image to request body

问题

我有一个image.Image的JPEG图像,我想将其解码为请求体。下面是简化的代码,但似乎永远无法完成请求。程序卡住了。

r, w := io.Pipe()
jpeg.Encode(w, img, &jpeg.Options{80})

req, e := http.NewRequest("PUT", myUrl, r)
if e != nil {
  return nil, e
}
http.DefaultClient.Do(req)

我该如何将图像写入请求体?

英文:

I have a jpeg image.Image and I want to decode to a request body. Simplified below, it doesn't seem to finish the request ever. The program hangs.

  r, w := io.Pipe()
  jpeg.Encode(w, img, &jpeg.Options{ 80 })

  req, e := http.NewRequest("PUT", myUrl, r)
  if e != nil {
    return nil, e
  }
  http.DefaultClient.Do(req)

How can I write an image to the request body?

答案1

得分: 2

只需使用缓冲区

var w bytes.Buffer

jpeg.Encode(&w, img, &jpeg.Options{80})

req, e := http.NewRequest("PUT", myUrl, &w)
if e != nil {
	log.Fatal(e)
}
http.DefaultClient.Do(req)
英文:

Just use a buffer

var w bytes.Buffer

jpeg.Encode(&w, img, &jpeg.Options{80})

req, e := http.NewRequest("PUT", myUrl, &w)
if e != nil {
	log.Fatal(e)
}
http.DefaultClient.Do(req)

答案2

得分: 1

jpeg.Encode无法进行处理,因为它被阻止写入管道(管道不具有缓冲区)。

你可以选择对编码后的图像进行缓冲,或者同时运行Encode和http请求。

// 确保对该通道进行缓冲,这样goroutine在我们提前返回时可以退出
errChan := make(chan error, 1)

r, w := io.Pipe()
go func() {
errChan <- jpeg.Encode(w, img, &jpeg.Options{80})
}()

req, err := http.NewRequest("PUT", myUrl, r)
if err != nil {
return nil, err
}
err = http.DefaultClient.Do(req)
if err != nil {
return nil, err
}

// 检查是否有编码错误
err = <-errChan
if err != nil {
return nil, err
}

英文:

jpeg.Encode can't procede, because it's blocked writing to the pipe (pipes don't buffer).

You either need to buffer the encoded image, or run the Encode and http request concurrently.

// make sure to buffer this channel, so the goroutine can exit if we return early
errChan := make(chan error, 1)

r, w := io.Pipe()
go func() {
	errChan &lt;- jpeg.Encode(w, img, &amp;jpeg.Options{80})
}()

req, err := http.NewRequest(&quot;PUT&quot;, myUrl, r)
if err != nil {
	return nil, err
}
err := http.DefaultClient.Do(req)
if err != nil {
	return nil, err
}

// check for an encoding error
err := &lt;-errChan
if err != nil {
	return nil, err
}

huangapple
  • 本文由 发表于 2014年7月12日 00:51:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/24702774.html
匿名

发表评论

匿名网友

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

确定