dplp5928 2017-11-20 15:23
浏览 114
已采纳

PUT上传带有流和进度的文件字节范围

I just got started with Go and need some help. I would like to upload a certain range of bytes from a file.

I already accomplished this by reading the bytes into a buffer. But this increases memory usage. Instead of reading bytes into memory, I want to stream them while uploading and have an upload progress. I did something like this in Node.js but struggle to get the puzzle pieces together for Go. The code that I have now looks like this:

func uploadChunk(id, mimeType, uploadURL, filePath string, offset, size uint) {
    // open file
    file, err := os.Open(filePath)
    panicCheck(err, ErrorFileRead) // custom error handler
    defer file.Close()

    // move to the proper byte
    file.Seek(int64(offset), 0)

    // read byte chunk into buffer
    buffer := make([]byte, size)
    file.Read(buffer)
    fileReader := bytes.NewReader(buffer)

    request, err := http.NewRequest(http.MethodPut, uploadURL, fileReader)

    client := &http.Client{
        Timeout: time.Second * 10,
    }

    response, err := client.Do(request)
    panicCheck(err, ErrorFileRead)

    defer response.Body.Close()

    b, err := httputil.DumpResponse(response, true)
    panicCheck(err, ErrorFileRead)
    fmt.Println("response
", string(b))
}

Could you guys help me to figure out how to stream and get progress for an upload?

Thanks

  • 写回答

1条回答 默认 最新

  • douchendan0040 2017-11-20 16:53
    关注

    You can use an io.LimitedReader to wrap the file and only read the amount of data you want. The implementation returned by io.LimitReader is an *io.LimitedReader.

    file.Seek(int64(offset), 0)
    fileReader := io.LimitReader(file, size)
    
    request, err := http.NewRequest(http.MethodPut, uploadURL, fileReader)
    

    And for S3 you will want to ensure that you don't use chunked encoding by explicitly setting the ContentLength:

    request.ContentLength = size
    

    As for upload progress, see: Go: Tracking POST request progress

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

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办