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
這很可能是一個錯誤,但即使這是預期的工作,也應該在文檔中提及。

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)
}
- 2 回答
- 0 關注
- 174 瀏覽
添加回答
舉報