Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang GET multipart form-data

Let say I have a html form

<form enctype="multipart/form-data" action="http://localhost:8080/incarcat" method="post">
    <input type="file" name="file" multiple="multiple"/>
    <input type="checkbox" name="delete" value="delete">
    <input type="submit" value="Load" />
</form>

and the following go code

read_form, err := req.MultipartReader()
for {
    part, err_part := read_form.NextPart()
    if err_part == io.EOF {
        break
    }
    if part.FormName() == "file" {
        //do something with files
    } else if part.FormName() == "delete" {
        //curata_folder()
        log.Println("delete is: ", part.Header.Get("delete"))
    }
}

How do i get the value of "delete"?

part.Header.Get("delete"))

it's not working

like image 532
Marinescu Bogdan Avatar asked Mar 09 '15 10:03

Marinescu Bogdan


2 Answers

The part implements the io.Reader interface. I am assuming what you are really asking is how to convert the part reader into a string, in the case that it is not a file. You can do so like this:

for {
   part, err_part := read_form.NextPart()
   if err_part == io.EOF {
      break
   }
   if part.FormName() == "delete" {
      buf := new(bytes.Buffer)
      buf.ReadFrom(part)
      log.Println("delete is: ", buf.String())
   } 
}
like image 80
gregtzar Avatar answered Oct 05 '22 21:10

gregtzar


You can probably content yourself by using the request.ParseMultipartForm method, then use the request.FormValue to get values as usual. Note that you also have the request.MultipartForm to get access to your files.

Example:

func(w http.ResponseWriter, r *http.Request) {
    // Here the parameter is the size of the form data that should
    // be loaded in memory, the remaining being put in temporary
    // files
    r.ParseMultipartForm(0)

    fmt.Println(r.FormValue("delete"))
}
like image 23
Elwinar Avatar answered Oct 05 '22 21:10

Elwinar