Sunday, September 24, 2023
HomeGolangIssues parsing HTTP POST multipart/form-data - Code Evaluate

Issues parsing HTTP POST multipart/form-data – Code Evaluate


Hi there, that is my first put up right here on this discussion board.
I’ve an issue in parsing multipart/form-data.
Here’s what I did:

func handleIncomingUploads(w http.ResponseWriter, r *http.Request){
        r.ParseMultipartForm(math.MaxInt64)

	log.Printf("%#v", r.Header.Get("Content material-Sort"))

	username:=r.FormValue("username")
	imei:=r.PostFormValue("imei")
	log.Println(username)
	log.Println(imei)

	file, handler, err:=r.FormFile("file")
	if err!=nil{
		log.Println("Error retrieving the file:", err)
		return
	}
	defer file.Shut()

	log.Printf("Uploaded File: %+vn", handler.Filename)
	log.Printf("File Dimension: %+vn", handler.Dimension)
	log.Printf("MIME Header: %+vn", handler.Header)


	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		log.Println(err)
	}

	filepath:="boom-"+username

	err=ioutil.WriteFile(filepath, fileBytes, 0777)
	if err != nil {
		log.Println(err)
	}

	log.Println("File efficiently uploaded.")
}

What I’m doing right here is making an attempt to parse a kind having three fields: username, imei and file.
The final one incorporates a file (clearly) and it’s properly parsed and saved by this code.
Now the issue is on the opposite two, they’re two string values, however they aren’t appropriately parsed, i’ve an empty string.

I made some makes an attempt utilizing Postman and I seen that these two fields are appropriately parsed provided that I select x-www-form-urlencoded as a substitute of form-data.
So I can’t perceive what’s incorrect right here. Can somebody assist me please?

Thanks prematurely.

Yesterday I lastly discovered the place the issue was (and it makes me really feel like an fool).
The issue is in ParseMultipartForm(math.MaxInt64), specifically within the parameter handed to the perform. Studying the docs I noticed what’s the function of this parameter, that’s to inform how a lot reminiscence have to be allotted in RAM to parse the info contained within the kind. Now, MaxInt64 is just a bit greater than the reminiscence obtainable on my machine… 8589934591 GB.

So the answer to my drawback was to set an accurate worth of reminiscence to allocate for parsing.

I’ve spent your complete day due to this, thanks a lot for posting! In my case, I couldn’t work out why it was working correctly regionally, however on deploy, the information have been merely empty. Altering the max to 0 solved it.

However, why would this occur? So far as I understood from the docs, the max is simply the utmost allowed to be allotted, not the minimal reminiscence required?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments