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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?