dqrdlqpo775594 2016-09-29 05:14
浏览 23
已采纳

您如何在流中上传文件?

There are a number of tutorials about posting files using http.Request in go, but almost invariably they start like this:

file, err := os.Open(path)
if err != nil {
    return nil, err
}
fileContents, err := ioutil.ReadAll(file)

Which is to say, you read the entire file into memory, and then convert it into a Buffer and pass that into a request, something like this:

func send(client *http.Client, file *os.File, endpoint string) {
    body := &bytes.Buffer{}
    io.Copy(body, file)
    req, _ := http.NewRequest("POST", endpoint, body)
    resp, _ := client.Do(req)
}

If you wanted to post a massive file and avoid reading it into memory, but instead steam the file up in chunks... how would you do that?

  • 写回答

2条回答 默认 最新

  • dpvmtdu364462 2016-09-29 23:53
    关注

    If you need to set Content-Length, it can be done manually. The following snippet is an example of uploading file and extra parameters as a stream (the code based on Buffer-less Multipart POST in Golang)

    //NOTE: for simplicity, error check is omitted
    func uploadLargeFile(uri, filePath string, chunkSize int, params map[string]string) {
        //open file and retrieve info
        file, _ := os.Open(filePath)
        fi, _ := file.Stat()
        defer file.Close()    
    
        //buffer for storing multipart data
        byteBuf := &bytes.Buffer{}
    
        //part: parameters
        mpWriter := multipart.NewWriter(byteBuf)
        for key, value := range params {
            _ = mpWriter.WriteField(key, value)
        }
    
        //part: file
        mpWriter.CreateFormFile("file", fi.Name())
        contentType := mpWriter.FormDataContentType()
    
        nmulti := byteBuf.Len()
        multi := make([]byte, nmulti)
        _, _ = byteBuf.Read(multi)    
    
        //part: latest boundary
        //when multipart closed, latest boundary is added
        mpWriter.Close()
        nboundary := byteBuf.Len()
        lastBoundary := make([]byte, nboundary)
        _, _ = byteBuf.Read(lastBoundary)
    
        //calculate content length
        totalSize := int64(nmulti) + fi.Size() + int64(nboundary)
        log.Printf("Content length = %v byte(s)
    ", totalSize)
    
        //use pipe to pass request
        rd, wr := io.Pipe()
        defer rd.Close()
    
        go func() {
            defer wr.Close()
    
            //write multipart
            _, _ = wr.Write(multi)
    
            //write file
            buf := make([]byte, chunkSize)
            for {
                n, err := file.Read(buf)
                if err != nil {
                    break
                }
                _, _ = wr.Write(buf[:n])
            }        
            //write boundary
            _, _ = wr.Write(lastBoundary)        
        }()
    
        //construct request with rd
        req, _ := http.NewRequest("POST", uri, rd)
        req.Header.Set("Content-Type", contentType)
        req.ContentLength = totalSize
    
        //process request
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        } else {
            log.Println(resp.StatusCode)
            log.Println(resp.Header)
    
            body := &bytes.Buffer{}
            _, _ = body.ReadFrom(resp.Body)
            resp.Body.Close()
            log.Println(body)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码