duanhao4156 2012-11-19 11:33
浏览 563
已采纳

如何在Golang中跟踪上传进度

i'm trying to track the upload progress in GOLANG, that's what i got at the moment

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条回答 默认 最新

  • douwei7976 2012-11-19 13:12
    关注

    This will work, a stream to calc the bytes read and the total progress you need to point the stream somewhere, in this code example I pointed it to a file.

    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 
    ",read )
                p = float32(read) / float32(length) *100
                fmt.Printf("progress: %v 
    ",p )
                dst.Write(buffer[0:cBytes])
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改