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

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

解析包含文件內容的 POST 請求正文

解析包含文件內容的 POST 請求正文

Go
長風秋雁 2022-10-24 15:07:35
我編寫了一個 HTTP 請求來發送文件內容:// HTTP request.req, err := UploadRequest("/slice", "file", pth)通過這個函數:// Creates a new file upload http request.// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84func UploadRequest(uri string, paramName, path string) (*http.Request, error) {    file, err := os.Open(path) // handle err...    fileContents, err := ioutil.ReadAll(file) // handle err...    fi, err := file.Stat() // handle err...    file.Close()    body := new(bytes.Buffer)    writer := multipart.NewWriter(body)    part, err := writer.CreateFormFile(paramName, fi.Name()) // handle err...    part.Write(fileContents)    err = writer.Close() // handle err...    request, err := http.NewRequest("POST", uri, body)    request.Header.Add("Content-Type", writer.FormDataContentType())    return request, err}問題請求處理程序接收請求正文:func Handler(w http.ResponseWriter, r *http.Request) {    switch r.Method {    case "POST":        body, err := ioutil.ReadAll(r.Body) // I have request body :)    }}調試器顯示請求body是:我試圖在\r\n\r\n字符之后獲取身體數據。我怎樣才能做到這一點?試過了這是嘗試過的,但沒有奏效:err = r.ParseForm() // Handle err...stl := r.PostForm.Get("file") // "file" param name is hard-coded.// `stl` is just an empty string.http去郵政
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

使用Request.FormFile解析多部分請求正文并返回文件:

func Handler(w http.ResponseWriter, r *http.Request) {

    switch r.Method {

    case "POST":

        f, h, err := r.FormFile(paramName)

        if err != nil {

            // TODO: Handle error

        }

        data, err := ioutil.ReadAll(f)

        if err != nil {

            // TODO: Handle error

        }

    }

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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