duang8642 2015-01-20 10:17 采纳率: 0%
浏览 82

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

I have a simple upload form as

<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>

And server side

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)
}

The problem is when I use enctype="multipart/form-data", I cannot get the value from client with r.PostFormValue, but it's ok if I set to enctype="application/x-www-form-urlencoded", go document say

PostFormValue returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored. PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions.

So why they did not say anything about enctype here ?

  • 写回答

2条回答 默认 最新

  • dtihe8614 2015-01-20 10:39
    关注

    If you use "multiplart/form-data" form-data encoding type you have to read form values with the Request.FormValue() function (note that not PostFormValue!).

    Change your defaultHandler() function to:

    func defaultHandler(w http.ResponseWriter, r *http.Request) {
        log.Println(r.FormValue("filepath"))
    }
    

    And it will work. The reason for this is because both Request.FormValue() and Request.PostFormValue() first call Request.ParseMultipartForm() if needed (if form encodying type is multipart and it has not yet been parsed) and Request.ParseMultipartForm() only stores the parsed form name-value pairs in the Request.Form and not in Request.PostForm: Request.ParseMultipartForm() source code

    This may well be a bug, but even if this is the intended working, it should be mentioned in the documentation.

    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真