英文:
How do i track the upload progress in golang
问题
我正在尝试在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)
}
}
英文:
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
得分: 8
这将起作用,一个stream用于计算读取的字节数和总进度,你需要将stream指向某个地方,在这个代码示例中,我将其指向了一个文件。
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])
}
}
}
英文:
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 \n",read )
p = float32(read) / float32(length) *100
fmt.Printf("progress: %v \n",p )
dst.Write(buffer[0:cBytes])
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论