英文:
Accessing array post params in golang (gin)
问题
我正在尝试访问一个由Gin(golang)编写的API中的文件和值数组。我有一个函数,它接受一个文件、高度和宽度。然后它调用函数来调整文件的大小,然后将其上传到S3。然而,我还尝试上传多个文件。
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})
}
我在文档中没有找到如何访问以下格式数据的任何地方:
item[0]file
item[0]width
item[0]height
item[1]file
item[1]width
item[1]height
等等。
我想到了以下类似的解决方案:
for index, element := range c.Request.PostForm("item") {
fmt.Println(element.Height)
}
但是报错了:"c.Request.Values undefined (type *http.Request has no field or method Values)"
英文:
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
得分: 3
你可以直接访问File
切片,而不是使用Request
上的FormFile
方法。假设你有一个与上传文件的顺序对应的width
和height
的表单数组。
if err := ctx.Request.ParseMultipartForm(32 << 20); err != nil {
// 处理错误
}
for i, fh := range ctx.Request.MultipartForm.File["item"] {
// 使用fh访问文件头
w := ctx.Request.MultipartForm.Value["width"][i]
h := ctx.Request.MultipartForm.Value["height"][i]
}
Request
上的FormFile
方法只是MultipartForm.File
的一个包装,它返回该键的第一个文件。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论