为了账号安全,请及时绑定邮箱和手机立即绑定

去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 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号