简体   繁体   中英

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.

I can upload a file alone with gin doing:

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.

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 )

Does anybody knows how to do that so that i can send a file + json in on request?

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.

You cant mix the JSON and Multipart form. 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!

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.

For this you could use the json.Unmarshal .

Here's a basic example of how to parse JSON string into a struct:

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

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.

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

{0x1400018e190 test0.png {123 john}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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