duanjingwei7239 2017-04-18 12:01
浏览 742

Beego如何访问使用multipart / form-data标头提交的参数?

I've ran into a problem as follows:
When I make a curl request to my beego app

curl http://localhost:8080/controller/path -X POST -H 'Content-Type: multipart/form-data; charset=UTF-8' -F “file=@file.csv;filename=file.csv” -F “name=first”

I want to access name param from my controller, but when I try

func (c *Controller) Path() {
...
var name string
c.Ctx.Input.Bind(&name, "name")
// or I've tried 'name := c.GetString("name")'
...
}

result is always an empty string as name variable.

What am I doing wrong ? How can I access params in this case ? Please any advice welcome !

Update 1
I've tried Parse to struct approach, with no luck...

type   DataParams struct {
  Name string `form:"name"`
}

    cLDP := DataParams{}
    if err := c.ParseForm(&cLDP); err != nil {
        return ret, err
    }  

Update 2
as of comment, I've tried

c.Ctx.Input.ParseFormOrMulitForm(99999)
var name string
c.Ctx.Input.Bind(&name, "name")

Update 3
after trying altogether I'm lost...

name := c.Ctx.Input.Query("name")
params := c.Ctx.Input.Params()
name2 := c.GetString("name")
c.Ctx.Input.ParseFormOrMulitForm(99999)
params2 := c.Ctx.Input.Params()
fmt.Println("Debug 2->", name)
fmt.Println("Debug 5->", name2)
fmt.Println("Debug 3->", params)
fmt.Println("Debug 4->", params2)

output is

Debug 2->
Debug 3-> map[...]
Debug 4-> map[...]
Debug 5->

no name param detected

Update 4
if I use c.Ctx.Input.RequestBody it not surprisingly is empty

And still no luck :(

  • 写回答

2条回答 默认 最新

  • dongtao1262 2017-04-18 16:22
    关注

    You should be able to access the name parameter value using the Query method, like so:

    name := c.Ctx.Input.Query("name")
    

    If you want to use Bind you can do something like this:

    names := []string{}
    if err := c.Ctx.Input.Bind(&names, "name"); err != nil {
        panic(err)
    }
    log.Println(name[0]) // first
    

    But you'll also have to update your curl to specifically declare the name parameter as an array with index:

    curl ... -F "name[0]=first"
    

    This is because internally Go stores a form's parameter values in a slice of strings (see url.Values) and beego is using this as well, so after beego parses the form it will look like this url.Values{"name": []string{"first"}} and so beego does not know how to bind []string{"first"} into a plain string.

    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器