douxuanou2787 2015-10-16 15:31
浏览 760
已采纳

在Golang(Gin)中访问数组发布参数

I'm attempting to access an array of files and values posted to an API written in Gin (golang). I've got a function which takes a file, height and width. It then calls functions to resize the file, and then upload it to S3. However, I'm attempting to also upload multiple files.

func (rc *ResizeController) Resize(c *gin.Context) {

    file, header, err := c.Request.FormFile("file")
    filename := header.Filename

    if err != nil {
        log.Fatal(err)
    }

    height := c.PostForm("height")
    width := c.PostForm("width")

    finalFile := rc.Crop(height, width, file)

    go rc.Upload(filename, finalFile, "image/jpeg", s3.BucketOwnerFull)

    c.JSON(200, gin.H{"filename": filename})
}

I couldn't see anywhere in the docs how to access data in the following format:

item[0]file
item[0]width
item[0]height
item[1]file
item[1]width
item[1]height

etc.

I figured something along the lines of:

for index, element := range c.Request.PostForm("item") {
    fmt.Println(element.Height)
}

But that threw "c.Request.Values undefined (type *http.Request has no field or method Values)"

  • 写回答

1条回答 默认 最新

  • dongxu1875 2015-10-16 15:57
    关注

    You can access the File slice directly instead of using the FormFile method on Request. Assuming you have a form array for width and height that correspond to the order that the files were uploaded.

    if err := ctx.Request.ParseMultipartForm(32 << 20); err != nil {
        // handle error
    }
    
    for i, fh := range ctx.Request.MultipartForm.File["item"] {
        // access file header using fh
        w := ctx.Request.MultipartForm.Value["width"][i]
        h := ctx.Request.MultipartForm.Value["height"][i]
    }
    

    The FormFile method on Request is just a wrapper around MultipartForm.File that returns the first file at that key.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥20 wpf datagrid单元闪烁效果失灵