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 关注
- 202 浏览
添加回答
举报
