如何在golang中跟踪上传进度

时间:2012-11-19 11:33:40

标签: http upload go progress

我正试图跟踪GOLANG的上传进度,这就是我现在所得到的

func Upload(w http.ResponseWriter, req *http.Request) {

    mr, err := req.MultipartReader()
    if err != nil {
        return
    }

    for {
        // var part *multipart.Part
        part, err := mr.NextPart()
        mr.partsRead

        if err == io.EOF {
            break
        }
        println(part)

    }

}

1 个答案:

答案 0 :(得分:8)

这将有效,可以计算读取的字节数以及将指向某处所需的总进度,在此代码示例中我将其指向文件

func Upload(w http.ResponseWriter, req *http.Request) {

    mr, err := req.MultipartReader()
    if err != nil {
        return
    }
    length := req.ContentLength
    for {

        part, err := mr.NextPart()
        if err == io.EOF {
            break
        }
        var read int64
        var p float32
        dst, err := os.OpenFile("dstfile", os.O_WRONLY|os.O_CREATE, 0644)
        if err != nil {
            return
        }
        for {
            buffer := make([]byte, 100000)
            cBytes, err := part.Read(buffer)
            if err == io.EOF {
                break
            }
            read = read + int64(cBytes)
            //fmt.Printf("read: %v \n",read )
            p = float32(read) / float32(length) *100
            fmt.Printf("progress: %v \n",p )
            dst.Write(buffer[0:cBytes])
        }
    }
}