douhong9210 2016-12-29 11:15
浏览 85
已采纳

(HTTP)通过将io.Reader从os.Open传递到http.Post(HTTP)来发布本地文件时,Content-Length为零

heya everyone: Got a short question, I would like to post(http) a file. I figured, since os.Open returns an io.Reader and http.Post takes an io.Reader I do not have read the file into memory in a separate step and can just pass around the Reader. However, the Content-Length will be set to zero- which kinda makes sense but is not what I need.

file, _ := os.Open("some file")
req, _ := http.NewRequest("POST", "some url", file)
dump, _ := httputil.DumpRequestOut(req, false)
fmt.Println(string(dump))

My question: Do i have to read the file into memory (with ioutil.ReadFile or some such) and make a new reader or is there a way to pass the reader from the file directly to the Post request without the "Reading" step?

I guess I could set the Content-Length by getting it via file.Stat, but I was wondering if there is a more elegant way of doing this?

  • 写回答

2条回答 默认 最新

  • douwen5584 2016-12-29 15:43
    关注

    Short answer is: you are absolutely right about giving the os.File to http.Request and about using os.File.Stat() to get the file size and setting it on the http.Request headers. Personally I've found it to be the simplest way around.

    i.e.

    file, _ := os.Open("some file")
    info, _ := file.Stat()
    req, _ := http.NewRequest("POST", "http://bla.com", file)
    req.ContentLength = info.Size()
    dump, _ := httputil.DumpRequestOut(req, false)
    fmt.Println(string(dump))
    

    Also note that as per http.Request.Write() documentation (I quote):

    If Body is present, Content-Length is <= 0 and TransferEncoding hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.

    So in that case the client itself would do the (arguably) most sensible thing to do for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀