7

我正在尝试跟踪 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)

    }

}
4

1 回答 1

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])
        }
    }
}
于 2012-11-19T13:12:10.343 回答