2017-01-24 1 views
0

API에 POST 요청을 보내고 제 3 자 라이브러리 (https://github.com/cheggaaa/pb)를 사용하고 있지만 파일 전송이 실제로 완료되기 전에 업로드 진행률 표시 줄이 완료됩니다.전송이 완료되기 전에 업로드 진행률 표시 줄이 끝나는 이유는 무엇입니까?

package main 

import(
    pb "gopkg.in/cheggaaa/pb.v1" 
    "net/http" 
) 

func main() { 
    file, e := os.Open(path) 
    if e != nil { 
     log.Fatal() 
    } 
    defer file.Close() 

    bar := pb.New(int(fi.Size())) 
    bar.Start() 


    req, err := http.NewRequest("POST", url, body) 

    resp, err := client.Do(req) 

    bar.Finish() 

    return 
} 

그것은

12.64 MB/12.64 MB [======================] 100.00% 12.59 MB/s 0s 

에서 시작 및 완료에 간다 :는 HTTP 필수 핸들러는 메모리에 파일을 읽고 진행 표시 줄이 증가하기 때문에

12.64 MB/12.64 MB [======================] 100.00% 626.67 KB/s 20s 

이 있습니까? 내가 뭘 놓치고 있니?

나는이 게시물 (Go: Tracking POST request progress)을 체크 아웃했는데, 내가 사용하고있는 라이브러리와 어떻게 다른지 알지 못했다. 이전에 진행 막대 막대를 읽는 버퍼에 io.Copy을 사용하여 시도했지만 요청이 전송되자 마자 똑같은 일을합니다. 내가 주석에 쓴대로

+1

코드가 불완전합니다. [Minimal, Complete, Verifiable example] (http://stackoverflow.com/help/mcve)을 제공해주십시오. –

답변

1

, 귀하의 질문은 필요한 모든 정보를 포함하지만 여기에 진행률 표시 줄과 원격 서버에 multipart-form의 파일을 게시 샘플 응용 프로그램입니다하지 않습니다

package main 

import (
    "github.com/cheggaaa/pb" 
    "os" 
    "time" 
    "bytes" 
    "mime/multipart" 
    "io" 
    "io/ioutil" 
    "net/http" 
) 

func main() { 
    body := &bytes.Buffer{} 
    bodyWriter := multipart.NewWriter(body) 

    fw, _ := bodyWriter.CreateFormFile("file", "filename.jpg") 
    fh, _ := os.Open("filename.jpg") 

    io.Copy(fw, fh) 
    bodyWriter.Close() 

    bar := pb.New(body.Len()).SetUnits(pb.U_BYTES).SetRefreshRate(time.Millisecond * 10) 
    bar.ShowSpeed = true 
    bar.Start() 

    reader := bar.NewProxyReader(body) 

    resp, _ := http.Post("http://domain.com", bodyWriter.FormDataContentType(), reader) 
    defer resp.Body.Close() 

    response, _ := ioutil.ReadAll(resp.Body) 
    print(string(response)) 
} 
+0

감사! 나는 multipart-form upload를 사용하기를 원하지 않거나 사용할 수 없다. 나는 그것이 효과가났다. –

0

있어 다른 패키지가 HTTP 요청에 문제를 일으키는 것으로 나타났습니다. 아래 코드는 완벽하게 작동합니다. 쉽게 문제를 해결하는 곳 저를주는 http://posttestserver.com

package main 

import(
    pb "gopkg.in/cheggaaa/pb.v1" 
    "fmt" 
    "os" 
    "log" 
    "io/ioutil" 
    "net/http" 
) 

func main() { 
    path := "/Users/me/testfile.txt" 
    file, e := os.Open(path) 
    if e != nil { 
     log.Fatal("File Error") 
    } 
    defer file.Close() 
    fi, e := file.Stat() 
    if e != nil { 
     log.Fatal("File Stat Error") 
    } 

    bar := pb.New(int(fi.Size())) 
    bar.Start() 

    client := &http.Client{} 
    req, e := http.NewRequest("POST", "http://posttestserver.com/post.php", bar.NewProxyReader(file)) 
    if e != nil { 
     log.Fatal("Request Error") 
    } 
    resp, e := client.Do(req) 
    if e != nil { 
     log.Fatal("Response Error") 
    } 
    bar.Finish() 
    respBody, e := ioutil.ReadAll(resp.Body) 
    fmt.Println(string(respBody)) 

    return 
} 

감사합니다!

관련 문제