duanhe1903 2018-04-10 21:21
浏览 55
已采纳

使用golang发送图像而不下载

What's the problem

I have a url with an image in it, and I want to send the image in a post request. Is there a way to do it without downloading the file locally?

What have I tried

Usually I would download the image, send the image, and delete the file. Is there a better way?

  response, e := http.Get(url)
if e != nil {
    log.Fatal(e)
} 
writer := multipart.NewWriter(body)
  part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  if err != nil {
      return nil, err
  }
  _, err = io.Copy(part, file)
  • 写回答

1条回答 默认 最新

  • doulu6929 2018-04-10 21:27
    关注

    You don't need to create a temporary file. Remember that http.Request takes an io.Reader (or an io.ReadCloser), and since response.Body is an io.ReadCloser it will happily read directly from your existing HTTP response body from your previous request.

    req, err := http.NewRequest("POST", url, response.Body)
    

    For a multipart upload, you can simply call multipart.CreatePart() and then io.Copy() directly from the response body of the original HTTP GET request to the writer you're using. You still don't need a temporary file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制