我正在嘗試在 go http 服務器中處理上傳的文件。但是調用ParseMultipartForm總是失敗并出現奇怪的錯誤:“ multipart: NextPart: EOF ” 盡管表單是有效的。調試它,我可以看到我得到了完整的編碼數據、大小和參數。然而它解析失敗。這是 html 表單:<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>這是相關的上傳功能:// upload logicfunc 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) }}無法理解為什么會這樣。這是我啟動服務器的方式: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)}
1 回答

肥皂起泡泡
TA貢獻1829條經驗 獲得超6個贊
它在句柄函數中。我在調用上傳函數之前讀取了所有的流數據。這是處理程序的修改代碼,現在一切正常:
func uploadLogoHandler(w http.ResponseWriter, r *http.Request) {
? ? writeToLog("uploadLogoHandler:" + r.URL.Path, "")
? ? upload(w, r)
}
如果我理解正確,那么錯誤:“multipart:NextPart:EOF”意味著表單是空的 - 它是空的,因為我之前清空了緩沖流。
希望它能幫助別人。
- 1 回答
- 0 關注
- 360 瀏覽
添加回答
舉報
0/150
提交
取消