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

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

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

报告相同问题?

悬赏问题

  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译