I'm creating an API in go with gin-gonic package, and I'm stuck with the file upload handler. Here is my code:
func postPicture(c *gin.Context) {
id, ok := c.Params.Get("fileId")
if !ok {...} // Err Handling
user, ok := c.Params.Get("user")
if !ok {...} // Err Handling
file, _, err := c.Request.FormFile("file") // Here is the bug
if err != nil {
Common.Debug("Error: " + err.Error())
c.JSON(http.StatusBadRequest, Common.JsonError{"Error", err.Error()})
return
} // Err Handling
path := "./Files/" + user + "/pictures"
filename := id + ".jpg"
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, 0755)
}
out, err := os.Create(path + "/" + filename)
if err != nil {...} // Err Handling
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {...} // Err Handling
c.JSON(http.StatusAccepted, gin.H{})
}
The error is on c.Request.FormFile(), it returns me "mime: invalid media parameter" whatever the request is. I tried the following:
curl -X POST --form upload=C:\Users\meiche_j\Pictures\Capture.PNG -H "Content-Type: multipart/form-data;boundary=???" "http://127.0.0.1:3003/postFiles/picture/58cbb5627067500f58834f69/fileIdTest"
curl -X POST --form upload=C:\Users\meiche_j\Pictures\Capture.PNG -H "Content-Type: multipart/form-data;boundary=???;Content-Disposition: attachment; filename=file" "http://127.0.0.1:3003/postFiles/picture/58cbb5627067500f58834f69/fileIdTest"
curl -X POST --form upload=C:\Users\meiche_j\Pictures\Capture.PNG -H "Content-Type: multipart/form-data;boundary=???;Content-Disposition: form-data; filename=file" "http://127.0.0.1:3003/postFiles/picture/58cbb5627067500f58834f69/fileIdTest"
I don't think the error is in the code, but I can't find what request headers are missing, any idea?
You make multiple little mistake in your code and in your test:
You should use the correct key in c.Request.FormFile("file")
, here you use file
as key but you use upload
in your curl request as key --form upload=...
You should use the @
in your curl request : curl -X POST --form upload=@C:\Users\meiche_j\Pictures\Capture.PNG
to indicate that you want to transfer the content of the file and not only the path
You should avoid putting by yourself the boundary parameter in your curl request and do a curl request like
curl -X POST -F upload=@pathtoyourfile -H 'Content-Type: multipart/form-data' "http://127.0.0.1:3003/postFiles/picture/58cbb5627067500f58834f69/fileIdTest"
Hope this has been usefull