【发布时间】:2017-04-02 17:32:54
【问题描述】:
我在玩 Mux 和 net/http。最近,我正在尝试使用一个带有一个端点的简单服务器来接受文件上传。
这是我目前得到的代码:
server.go
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
router := mux.NewRouter()
router.
Path("/upload").
Methods("POST").
HandlerFunc(UploadCsv)
fmt.Println("Starting")
log.Fatal(http.ListenAndServe(":8080", router))
}
endpoint.go
package main
import (
"fmt"
"net/http"
)
func UploadFile(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(5 * 1024 * 1024)
if err != nil {
panic(err)
}
fmt.Println(r.FormValue("fileupload"))
}
我想我已经将问题缩小到实际从UploadFile 中的请求中检索正文。当我运行这个 cURL 命令时:
curl http://localhost:8080/upload -F "fileupload=@test.txt" -vvv
我得到一个空响应(如预期的那样;我没有打印到ResponseWriter),但我只是在运行服务器的提示符处打印了一个新的(空)行,而不是请求身体。
我将文件作为多部分发送(AFAIK,通过在 cURL 中使用 -F 而不是 -d 暗示),并且 cURL 的详细输出显示已发送 502 个字节:
$ curl http://localhost:8080/upload -F "fileupload=@test.txt" -vvv
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /upload HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> Content-Length: 520
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------b578878d86779dc5
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Fri, 18 Nov 2016 19:01:50 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
在 Go 中使用 net/http 服务器接收作为多部分表单数据上传的文件的正确方法是什么?
【问题讨论】:
-
这也是我用来解析多个文件的方法:golang.org/pkg/mime/multipart/#Form
-
@mh-cbon 就是这样!我得到了一个
[]byte,它可以正确打印,这意味着我有一些东西可以使用。谢谢! -
@mh-cbon 请将您的答案添加为答案,以便将其标记为已接受,并且可以在人们寻找要回答的问题时过滤掉此问题。
标签: go multipartform-data httpserver