【问题标题】:Gin-Gonic File upload mime errorGin-Gonic 文件上传 mime 错误
【发布时间】:2017-08-09 04:53:26
【问题描述】:

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

我认为错误不在代码中,但我找不到缺少哪些请求标头,知道吗?

【问题讨论】:

  • 你可以尝试使用'强制'内容'部分成为文件,在文件名前加上@符号',即 curl -X POST --form file=@C:\Users\ meiche_j\Pictures\Capture.PNG....

标签: go file-upload go-gin


【解决方案1】:

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

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

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

  3. 您应该避免自己在 curl 请求中放置边界参数,并执行类似的 curl 请求

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

希望对你有用

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2022-01-23
    • 2018-11-07
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2015-09-04
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多