doutandusegang2961 2017-02-15 22:37 采纳率: 0%
浏览 29
已采纳

通过http POST发送os.Stdin而不将文件加载到内存中

I am trying to send a file to a server via a POST request. To accomplish this, I use the following code:

func newfileUploadRequest(uri string) (*http.Request, error) {

    body := new(bytes.Buffer)
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile("file", "file")
    if err != nil {
        return nil, err
    }
    io.Copy(part, os.Stdin)

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    request, err := http.NewRequest("POST", uri, body)
    if err != nil {
        return nil, err
    }
    request.Header.Set("Content-Type", writer.FormDataContentType())
    return request, nil
}


func main() {
    r, err := newfileUploadRequest("http://localhost:8080/")
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(r)
    if err != nil {
        panic(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    print(string(body))
}

While this works well, it is my understanding that io.Copy will copy the entire file into memory before the POST request is sent. Large files (multiple GB) will create issues. Is there a way to prevent this? I found this, but that simply says to use io.Copy.

  • 写回答

2条回答 默认 最新

  • dougutuo9879 2017-02-15 23:19
    关注

    You can avoid copying the data in memory by using an io.Pipe and a goroutine that copies from the file to the pipe:

    func newfileUploadRequest(uri string) (*http.Request, error) {
      r, w := io.Pipe()
      writer := multipart.NewWriter(w)
      go func() {
        part, err := writer.CreateFormFile("file", "file")
        if err != nil {
            w.CloseWithError(err)
            return
        }
        _, err = io.Copy(part, os.Stdin)
        if err != nil {
            w.CloseWithError(err)
            return
        }
        err = writer.Close()
        if err != nil {
            w.CloseWithError(err)
            return
        }
      }()
    
      request, err := http.NewRequest("POST", uri, r)
      if err != nil {
        return nil, err
      }
      request.Header.Set("Content-Type", writer.FormDataContentType())
      return request, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?