gpt4 book ai didi

go - Gin-Gonic 文件上传 mime 错误

转载 作者:IT王子 更新时间:2023-10-29 02:32:43 31 4
gpt4 key购买 nike

我正在使用 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"

我不认为错误出在代码中,但我找不到缺少的请求 header ,知道吗?

最佳答案

您在代码和测试中犯了多个小错误:

  1. 您应该在 c.Request.FormFile("file") 中使用正确的 key ,这里您使用 file 作为 key ,但您使用 upload 在你的 curl 请求中作为键 --form upload=...

  2. 你应该在你的 curl 请求中使用 @ : curl -X POST --form upload=@C:\Users\meiche_j\Pictures\Capture.PNG表示你要传输文件的内容而不仅仅是路径

  3. 你应该避免在你的 curl 请求中自己放置 boundary 参数,并且像

    这样的 curl 请求
    curl -X POST -F upload=@pathtoyourfile -H 'Content-Type: multipart/form-data' "http://127.0.0.1:3003/postFiles/picture/58cbb5627067500f58834f69/fileIdTest"

希望对你有用

关于go - Gin-Gonic 文件上传 mime 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42860784/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com