亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

多部分編寫器創建表單文件卡住

多部分編寫器創建表單文件卡住

Go
慕勒3428872 2022-09-05 10:24:28
嘗試使用 go 發布多部分/表單數據圖像圖像文件從請求客戶端接收,并且已另存為多部分。文件這是我的代碼func postImage(file multipart.File, url string, filename string) (*http.Response, error) {    r, w := io.Pipe()    defer w.Close()    m := multipart.NewWriter(w)    defer m.Close()    errchan := make(chan error)    defer close(errchan)    go func() {        part, err := m.CreateFormFile("file", filename)        log.Println(err)        if err != nil {            errchan <- err            return        }        if _, err := io.Copy(part, file); err != nil {            errchan <- err            return        }    }()    merr := <-errchan    if merr != nil {        return nil, merr    }    resp, err := http.Post(url, m.FormDataContentType(), r)    if err != nil {        return nil, err    }    defer resp.Body.Close()    return resp, err}當我嘗試使用它時,它卡在永遠不會返回任何東西part, err := m.CreateFormFile("file", filename)任何解決方案?
查看完整描述

1 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

使用管道錯誤將錯誤傳播回主 goroutine。關閉管道的寫入端,以防止客戶端在讀取時永久阻塞。關閉管道的讀取側,以確保 goroutine 退出。


func postImage(file multipart.File, url string, filename string) (*http.Response, error) {

    r, w := io.Pipe()


    // Close the read side of the pipe to ensure that

    // the goroutine exits in the case where http.Post

    // does not read all of the request body.

    defer r.Close()


    m := multipart.NewWriter(w)


    go func() {

        part, err := m.CreateFormFile("file", filename)

        if err != nil {

            // The error is returned from read on the pipe.

            w.CloseWithError(err)

            return

        }

        if _, err := io.Copy(part, file); err != nil {

            // The error is returned from read on the pipe.

            w.CloseWithError(err)

            return

        }

        // The http.Post function reads the pipe until 

        // an error or EOF. Close to return an EOF to

        // http.Post.

        w.Close()

    }()


    resp, err := http.Post(url, m.FormDataContentType(), r)

    if err != nil {

        return nil, err

    }

    defer resp.Body.Close()


    return resp, err

}


查看完整回答
反對 回復 2022-09-05
  • 1 回答
  • 0 關注
  • 76 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號