golang 文件上传失败

标签 file go upload multipart

在我的用例中,我试图将文件上传到 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错误。

谁能帮我解决这个问题?

最佳答案

老实说,我不知道你是怎么出错的,因为你的 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>

关于golang 文件上传失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826612/

相关文章:

go - 在没有根文件夹的文件夹中压缩内容

html - 在linux下的firefox浏览器中浏览ftp文件

c - 什么会导致 "regular"类型的文件在 Linux 中不可读以及如何识别这个

go - 惯用地干掉 Go 中的公共(public)字段

go - grpc 服务器中的依赖注入(inject)

html - 使用 remotipart 提交带有文件输入的表单包装一个文本区域以响应

PHP post_max_size 覆盖upload_max_filesize

file - 让 CMake 将生成的二进制文件与 Assets 一起放在特定的目录结构中

ios - 从 Swift IOS 套接字获取 InputStream 中的文件

node.js - 乔基达尔 : onchange event for a file is possibly triggered to fast