普通网友 2016-03-06 12:01
浏览 146
已采纳

Golang中的文件上传失败

In my use case I am trying to upload a file to server in golang. I have the following html code,

<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>

And the server side,

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)
}

When I try to upload the file, I am getting request Content-Type isn't multipart/form-data error in server side.

Could anyone help me on this?

  • 写回答

2条回答 默认 最新

  • duanfengtuo6012 2016-03-06 12:17
    关注

    To be honest I have no idea how do you even get error as your HTML is not form. But I think you getting error because by default form is send as GET request while multipart/form-data should be send via POST. Here is example of minimal form which should work.

    <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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决