我正在使用 gin-gonic 包创建一个 API,并且我坚持使用文件上传处理程序。这是我的代码:
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{})
}
错误出现在 c.Request.FormFile() 上,无论请求是什么,它都会返回“mime:无效的媒体参数”。我尝试了以下方法:
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"
我认为错误不在代码中,但是我找不到缺少哪些请求标头,知道吗?