-1

I tried to send form data and file to server but from the server the form value is empty , but i receive file only

SERVER

func CreatePost(w http.ResponseWriter, r *http.Request) {
    createdAt := time.Now().String()
    r.ParseForm()
    data := r.PostForm.Get("body")
    fmt.Println(r.PostForm)
    r.ParseMultipartForm(10 << 20)
    file, header, err := r.FormFile("file")
    ///Some Codes///////
}

TERMINAL OUTPUT

19:33:08 app         | listerning on 8080
19:33:11 app         | map[]

CLICK ME

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user9116815
  • 23
  • 1
  • 10

1 Answers1

4

According to the docs for ParseForm:

For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

When you submit a file, the content type will be one of the multipart types.

Based on these docs, I'd try this:

 r.ParseMultipartForm(10<<20)
 data := r.PostForm.Get("body")
 fmt.Println(r.PostForm)
 file, header, err := r.FormFile("file")
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Thanks bro its working btw why should i do this? Can you please explain? – user9116815 Jul 20 '20 at 14:41
  • 1
    When you submit a file, the request type will be multipart/formdata, and the request will have multiple parts. One part will contain the form data, and other parts will contain the files. ParseMultiPart parses the form data and those files. PartForm only parses URL encoded form data. – Burak Serdar Jul 20 '20 at 14:43