简体   繁体   English

如何使用gin gonic上传多部分文件和Go中的json?

[英]how to upload multipart file and json in Go with gin gonic?

I'm trying to upload a file to my server with additional information attached to it as json.我正在尝试将文件上传到我的服务器,附加信息为 json。

I can upload a file alone with gin doing:我可以用 gin 单独上传一个文件:

file, err := c.FormFile("file")
if err != nil {
    return error
}

But i can't figure out how to pass the file AND the json at the same time.但我不知道如何同时传递文件和 json。

type FileJson struct {
    Name        string          `json:"name" binding:"required"`
    Description string           `json:"description"`
    fileData    *multipart.FileHeader `form:"file"`
}

func UploadFile(c *gin.Context) {
    var testmultipart fileJSON
    err := c.Bind(&testmultipart)
    if err != nil {
        return err
    }
    c.JSON(http.StatusOK, gin.H{"status": http.StatusText(http.StatusOK), "data": "xx"})
}

This doesn't work and doesn't unparse the json data into the struct ( either fialing on the required tag or just having empty field inside the struct )这不起作用,也不会将 json 数据解析到结构中(要么在必需的标记上失败,要么在结构中只有空字段)

Does anybody knows how to do that so that i can send a file + json in on request?有人知道该怎么做,以便我可以根据要求发送文件 + json 吗?

One solution would be to encode the file to base64 and unparse it as a []byte but that shouldn't be necessary and make the request larger so i want to do it with mime/multipart.一种解决方案是将文件编码为 base64 并将其解析为 [] 字节,但这不是必需的,并使请求更大,所以我想用 mime/multipart 来完成。

You cant mix the JSON and Multipart form.您不能混合使用 JSON 和 Multipart 表单。 Your Name and Description fields appear empty since you have not added the "form" tag for them.您的名称和描述字段显示为空,因为您尚未为它们添加“表单”标签。

type FileJson struct {
    Name        string                `form:"name" binding:"required"`
    Description string                `form"description"`
    fileData    *multipart.FileHeader `form:"file"`
}

But I need JSON!但我需要 JSON!

To send File and Json in a request you could pass the JSON as a value of one of the form fields and parse it again after the Bind call.要在请求中发送 File 和 Json,您可以将 JSON 作为表单字段之一的值传递,并在 Bind 调用之后再次解析它。

For this you could use the json.Unmarshal .为此,您可以使用json.Unmarshal

Here's a basic example of how to parse JSON string into a struct:这是一个如何将 JSON 字符串解析为结构的基本示例:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    var fileMeta struct{
        Title       string `json:"title"`
        Description string `json:"description"`
    }

    json.Unmarshal([]byte(`{"title":"Foo Bar", "description":"Bar by Foo"}`), &fileMeta)

    fmt.Println(fileMeta.Title)
    fmt.Println(fileMeta.Description)
}

See a longer playground example: https://play.golang.org/p/aFv2XMijTWV查看更长的游乐场示例:https: //play.golang.org/p/aFv2XMijTWV

But that's ugly但这很丑

In case you are wondering how to handle REST file uploads with JSON meta data then the following article HTTP/REST API File Uploads provides some great ideas.如果您想知道如何使用 JSON 元数据处理 REST 文件上传,那么以下文章HTTP/REST API 文件上传提供了一些很棒的想法。

Use form Data to append file,name and description.使用表单数据附加文件、名称和描述。

To extract values:要提取值:

form, err := c.MultipartForm()

files := form.File["file"]

name = form.Value["title"]

description = form.Value["description"]

With github.com/gin-gonic/gin v1.8.1github.com/gin-gonic/gin v1.8.1

You can do like this:你可以这样做:

type SomeStruct struct {
  Id   int64  `json:"id"`
  Name string `json:"name"`
}

type SomeRequest struct {
  File        *multipart.FileHeader `form:"file"`
  Path        string                `form:"path"`
  StructField SomeStruct            `form:"structField"`
}

func handle(c *gin.Context) error {
    var req SomeRequest
    if err := _c.ShouldBind(&req); err != nil {
      return err
    }
    fmt.Println(req)
}

Test it:测试它:

curl -X 'POST' \
  'http://the-url' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@test0.png;type=image/png' \
  -F 'path=test0.png' \
  -F 'structField={
  "id": 123,
  "name": "john"
}'

And the output is:而 output 是:

{0x1400018e190 test0.png {123 john}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM