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

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

去http服務器處理POST數據的區別?

去http服務器處理POST數據的區別?

Go
墨色風雨 2021-09-13 09:54:54
我有一個簡單的上傳表單<html><title>Go upload</title><body><form action="http://localhost:8899/up" method="post" enctype="multipart/form-data"><label for="file">File Path:</label><input type="text" name="filepath" id="filepath"><p><label for="file">Content:</label><textarea name="jscontent" id="jscontent" style="width:500px;height:100px" rows="10" cols="80"></textarea><p><input type="submit" name="submit" value="Submit"></form></body></html>和服務器端package main import (    "net/http"    "log")func defaultHandler(w http.ResponseWriter, r *http.Request) {    log.Println(r.PostFormValue("filepath"))}func main() {    http.HandleFunc("/up", defaultHandler)    http.ListenAndServe(":8899", nil)}問題是當我使用 時enctype="multipart/form-data",我無法從客戶端獲取值r.PostFormValue,但是如果我設置為 就可以了enctype="application/x-www-form-urlencoded",去文檔說PostFormValue 返回 POST 或 PUT 請求正文的命名組件的第一個值。URL 查詢參數被忽略。PostFormValue 會在必要時調用 ParseMultipartForm 和 ParseForm 并忽略這些函數返回的任何錯誤。那么為什么他們沒有說到enctype這里呢?
查看完整描述

2 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

如果您使用"multiplart/form-data"表單數據編碼類型,您必須使用Request.FormValue()函數讀取表單值(注意不是PostFormValue?。?。


將您的defaultHandler()功能更改為:


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

    log.Println(r.FormValue("filepath"))

}

它會起作用。這樣做的原因是因為Request.FormValue()和Request.PostFormValue()firstRequest.ParseMultipartForm()在需要時調用(如果表單編碼類型是multipart并且尚未解析)并且Request.ParseMultipartForm()只將解析的表單名稱-值對存儲在 theRequest.Form而不是 in Request.PostForm:Request.ParseMultipartForm() source code


這很可能是一個錯誤,但即使這是預期的工作,也應該在文檔中提及。


查看完整回答
反對 回復 2021-09-13
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

如果您嘗試上傳需要使用multipart/form-dataenctype 的文件,則輸入字段必須是type=file并使用FormFile代替PostFormValue(僅返回字符串)方法。


<html>

<title>Go upload</title>

<body>

    <form action="http://localhost:8899/up" method="post" enctype="multipart/form-data">

        <label for="filepath">File Path:</label>

        <input type="file" name="filepath" id="filepath">

        <p>

        <label for="jscontent">Content:</label>

        <textarea name="jscontent" id="jscontent" style="width:500px;height:100px" rows="10" cols="80"></textarea>

        <p>

        <input type="submit" name="submit" value="Submit">

    </form>

</body>

</html>

package main


import (

    "log"

    "net/http"

)


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

    file, header, err := r.FormFile("filepath")


    defer file.Close()


    if err != nil {

        log.Println(err.Error())

    }


    log.Println(header.Filename)


    // Copy file to a folder or something

}

func main() {

    http.HandleFunc("/up", defaultHandler)

    http.ListenAndServe(":8899", nil)

}


查看完整回答
反對 回復 2021-09-13
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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