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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么