去http服务器处理POST数据的区别?

我有一个简单的上传表单


<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这里呢?


墨色风雨
浏览 203回答 2
2回答

喵喵时光机

如果您使用"multiplart/form-data"表单数据编码类型,您必须使用Request.FormValue()函数读取表单值(注意不是PostFormValue!)。将您的defaultHandler()功能更改为:func defaultHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; log.Println(r.FormValue("filepath"))}它会起作用。这样做的原因是因为Request.FormValue()和Request.PostFormValue()firstRequest.ParseMultipartForm()在需要时调用(如果表单编码类型是multipart并且尚未解析)并且Request.ParseMultipartForm()只将解析的表单名称-值对存储在 theRequest.Form而不是 in Request.PostForm:Request.ParseMultipartForm() source code这很可能是一个错误,但即使这是预期的工作,也应该在文档中提及。

繁华开满天机

如果您尝试上传需要使用multipart/form-dataenctype 的文件,则输入字段必须是type=file并使用FormFile代替PostFormValue(仅返回字符串)方法。<html><title>Go upload</title><body>&nbsp; &nbsp; <form action="http://localhost:8899/up" method="post" enctype="multipart/form-data">&nbsp; &nbsp; &nbsp; &nbsp; <label for="filepath">File Path:</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="file" name="filepath" id="filepath">&nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; <label for="jscontent">Content:</label>&nbsp; &nbsp; &nbsp; &nbsp; <textarea name="jscontent" id="jscontent" style="width:500px;height:100px" rows="10" cols="80"></textarea>&nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" name="submit" value="Submit">&nbsp; &nbsp; </form></body></html>package mainimport (&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http")func defaultHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; file, header, err := r.FormFile("filepath")&nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(err.Error())&nbsp; &nbsp; }&nbsp; &nbsp; log.Println(header.Filename)&nbsp; &nbsp; // Copy file to a folder or something}func main() {&nbsp; &nbsp; http.HandleFunc("/up", defaultHandler)&nbsp; &nbsp; http.ListenAndServe(":8899", nil)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go