Ewan Valentine
Ewan Valentine

Reputation: 3961

Accessing array post params in 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)"

Upvotes: 2

Views: 2729

Answers (1)

jmaloney
jmaloney

Reputation: 12300

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.

Upvotes: 3

Related Questions