Go-接受http post多部分文件

Go-接受http post多部分文件,http,post,go,multipart,Http,Post,Go,Multipart,我正在试图弄清楚如何在Go中接受/接收HTTP Post。我只想能够接收一个文件,获取它的mime类型并将文件保存在本地 我已经搜索了一整天,但我能找到的只是如何将文件发送到某个远程位置,但我发现没有一个例子能涵盖接收它 任何帮助都将不胜感激 以贾斯蒂纳斯为例,结合我现有的实验,我已经走到了这一步,但m.Post似乎从未被叫来 package main import ( "fmt" "io" "net/http" "os" "github.com/cod

我正在试图弄清楚如何在Go中接受/接收HTTP Post。我只想能够接收一个文件,获取它的mime类型并将文件保存在本地

我已经搜索了一整天,但我能找到的只是如何将文件发送到某个远程位置,但我发现没有一个例子能涵盖接收它

任何帮助都将不胜感激

以贾斯蒂纳斯为例,结合我现有的实验,我已经走到了这一步,但m.Post似乎从未被叫来

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "github.com/codegangsta/martini"
    "github.com/codegangsta/martini-contrib/render"
)

func main() {

    m := martini.Classic()

    m.Use(render.Renderer(render.Options{
        Directory: "templates", // Specify what path to load the templates from.
        Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
        Charset: "UTF-8", // Sets encoding for json and html content-types.
    }))


    m.Get("/", func(r render.Render) {
        fmt.Printf("%v\n", "g./")
        r.HTML(200, "hello", "world")
    })

    m.Get("/:who", func(args martini.Params, r render.Render) {
        fmt.Printf("%v\n", "g./:who")
        r.HTML(200, "hello", args["who"])
    })

    m.Post("/up", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("%v\n", "p./up")

        file, header, err := r.FormFile("file")
        defer file.Close()

        if err != nil {
            fmt.Fprintln(w, err)
            return
        }

        out, err := os.Create("/tmp/file")
        if err != nil {
            fmt.Fprintf(w, "Failed to open the file for writing")
            return
        }
        defer out.Close()
        _, err = io.Copy(out, file)
        if err != nil {
            fmt.Fprintln(w, err)
        }

        // the header contains useful info, like the original file name
        fmt.Fprintf(w, "File %s uploaded successfully.", header.Filename)
    })

    m.Run()
}

Go的
net/http
服务器在后台使用
mime/multipart
包处理这个问题。您只需在
*http.Request
上调用
r.FormFile()
,即可获得回复

。以及使用curl上载文件的结果:

justinas@ubuntu /tmp curl -i -F file=@/tmp/stuff.txt http://127.0.0.1:8080/
HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Tue, 24 Dec 2013 20:56:07 GMT
Content-Length: 37
Content-Type: text/plain; charset=utf-8

File stuff.txt uploaded successfully.%                                                                                              
justinas@ubuntu /tmp cat file
kittens!

谢谢你,我来看看。我相信它会起作用,因为我从我读过的一些其他示例/github中认出了你的名字。我已经用我现有的代码和你的代码更新了原始问题。关于我做错了什么有什么建议吗?你的例子(再次使用curl)。HTML表单中可能存在问题,而Go处理程序中可能没有。首先,一个常见的问题是忘记设置正确的
enctype
()。谢谢!原来问题不在于Go,而在于nginx的最大上传文件大小。改为50MB,航行良好。