Reputation: 2809
I am trying to handle uploaded files in go http server. But calling ParseMultipartForm always fails with strange error: "multipart: NextPart: EOF" although the form is valid. Debugging it, I can see that I get the full encoded data, and size and parameters. Yet it fails parsing.
Here is the html form:
<html>
<head>
<title>Upload file</title>
</head>
<body>
<form enctype="multipart/form-data" action="http://localhost:8080/uploadLogo/" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{{.}}" />
<input type="submit" value="upload" />
</form>
</body>
</html>
And here is the relevant upload function:
// upload logic
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
// crutime := time.Now().Unix()
// h := md5.New()
// io.WriteString(h, strconv.FormatInt(crutime, 10))
// token := fmt.Sprintf("%x", h.Sum(nil))
// t, _ := template.ParseFiles("upload.gtpl")
// t.Execute(w, token)
} else {
err := r.ParseMultipartForm(5 * 1024 * 1024 * 1024)
if err != nil {
fmt.Println("Error ParseMultipartForm: ", err) // here it fails !!! with: "multipart: NextPart: EOF"
return
}
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println("Error parsing file", err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
fmt.Println("filename:", handler.Filename)
f, err := os.OpenFile(logosDir + handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
Couldn't understand why that happens.
Here is how I start my server:
func uploadLogoHandler(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintf(w, "viewLogoHandler, Path: %s!", r.URL.Path[1:])
bodyBytes, _ := ioutil.ReadAll(r.Body)
bodyString := string(bodyBytes)
writeToLog("uploadLogoHandler:" + r.URL.Path, "bodyString length:" + strconv.Itoa(len(bodyString)))
upload(w, r)
}
///////////////////////////////////////////////////////////////////////////////////////
// main
func main() {
if(len(os.Args) < 2) {
fmt.Println("Usage: receiver [port number]")
os.Exit(1)
}
port := os.Args[1]
s := &http.Server{
Addr: ":" + port,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
http.HandleFunc("/uploadLogo/", uploadLogoHandler)
http.HandleFunc("/", handler)
log.Fatal(s.ListenAndServe())
}
Upvotes: 1
Views: 4397
Reputation: 2809
As writing the question I have already found the problem. It is in the handle function. I read all the stream data before calling the upload function. Here is the revised code of the handler, and now everything works:
func uploadLogoHandler(w http.ResponseWriter, r *http.Request) {
writeToLog("uploadLogoHandler:" + r.URL.Path, "")
upload(w, r)
}
If I understand correctly so the error: "multipart: NextPart: EOF" means that the form is empty - and it was empty because I emptied the buffer stream before.
Hope it will help others. Best.
Upvotes: 2