【问题标题】:File upload failing in golanggolang中文件上传失败
【发布时间】:2016-06-19 23:48:49
【问题描述】:

在我的用例中,我正在尝试将文件上传到 golang 中的服务器。我有以下html代码,

<div class="form-input upload-file" enctype="multipart/form-data" >
    <input type="file"name="file" id="file" />
    <input type="hidden"name="token" value="{{.}}" />
    <a href="/uploadfile/" data-toggle="tooltip" title="upload">
        <input type="button upload-video" class="btn btn-primary btn-filled btn-xs" value="upload" />
    </a>
</div>

还有服务器端,

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    // the FormFile function takes in the POST input id file
    file, header, err := r.FormFile("file")
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }
    defer file.Close()

    out, err := os.Create("/tmp/uploadedfile")
    if err != nil {
        fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
        return
    }
    defer out.Close()

    // write the content from POST to the file
    _, err = io.Copy(out, file)
    if err != nil {
        fmt.Fprintln(w, err)
    }

    fmt.Fprintf(w, "File uploaded successfully : ")
    fmt.Fprintf(w, header.Filename)
}

当我尝试上传文件时,我在服务器端收到request Content-Type isn't multipart/form-data 错误。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: file go upload multipart


    【解决方案1】:

    说实话,我不知道你是怎么得到错误的,因为你的 HTML 不是表单。但我认为你会出错,因为默认情况下表单是作为 GET 请求发送的,而 multipart/form-data 应该通过 POST 发送。这是应该工作的最小形式的示例。

    <form action="/uploadfile/" enctype="multipart/form-data" method="post">
        <input type="file" name="file" id="file" />
        <input type="hidden"name="token" value="{{.}}" />
        <input type="submit" value="upload" />
    </form>
    

    【讨论】:

    • 谢谢。我正在尝试在另一种形式中使用它。所以我尝试了这种方式。有什么办法可以在另一种形式中使用它吗?会很有帮助的
    • @DineshAppavoo 表单内的表单?
    • 看起来不可能nest-forms。我试过了,原来的表格正在崩溃。有什么解决方法吗?
    • @DineshAppavoo 我能想象的只有一个“解决方法”是通过 AJAX 发送文件并将它们的 ID 放入“父”形式。但是我不明白如果你可以发送一个带有字段和文件的表单,你为什么需要嵌套表单。
    【解决方案2】:

    问题是您必须包含包含内容类型的标头。

    req.Header.Add("Content-Type", writer.FormDataContentType())
    

    这包含在mime/multipart 包中。

    有关工作示例,请查看 this 博客文章。

    【讨论】:

    • 他没有尝试从 Go 应用程序发送表单。他无法在 Go 应用程序中获取 HTML 表单数据。
    • 是的,这就是他收到上述错误的原因。
    • 他的 Go 代码与正确的 HTML 格式完美配合。您的链接是关于将数据从 Go 发送到远程服务。
    猜你喜欢
    • 2013-06-09
    • 2012-03-18
    • 1970-01-01
    • 2013-07-09
    • 2020-06-12
    • 2012-05-31
    相关资源
    最近更新 更多