func fupload(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
company := r.FormValue("company")
fmt.Println(company)
_, header, _ := r.FormFile("upfile")
fmt.Println(header.Filename)
return
}
w.Write([]byte("<html><body>"))
w.Write([]byte(fmt.Sprintf("<form method=\"POST\" enctype=\"multipart/form-data\">")))
w.Write([]byte("Enter Company <input type=\"text\" maxlength=\"80\" size=\"80\" name=\"company\" ><br/>"))
w.Write([]byte("File to upload: <input type=\"file\" name=\"upfile\" /><br/>"))
w.Write([]byte("<input type=\"submit\" value=\"Submit\"/>"))
w.Write([]byte("</form>"))
w.Write([]byte("</body></html>"))
return
}
For the input type Text (eg) Company here always return NULL, when enctype="multipart/form-data"
ParseForm
only parses the query parameters. From the docs:
ParseForm parses the raw query from the URL and updates r.Form.
For POST or PUT requests, it also parses the request body as a form and put the results into both r.PostForm and r.Form. POST and PUT body parameters take precedence over URL query string values in r.Form.
If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.
ParseMultipartForm calls ParseForm automatically. It is idempotent.
Either use ParseMultipartForm
if you want to handle "multipart/form-data", or don't call either and let FormValue
call what's needed.
Yes, you should use enctype="multipart/form-data". But you should not use ParseForm() method if you already use FormValue(key string) or FormFile(key string) method.
FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.
FormValue returns the first value for the named component of the query. POST and PUT body parameters take precedence over URL query string values. FormValue calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.
<form action="/fupload" method="POST" enctype="multipart/form-data">
<input type="file" name="fileupload">
</form>
file, _, err := req.FormFile("fileupload")
switch err {
case nil:
defer file.Close()
fileData, err := ioutil.ReadAll(file)
//check err
case http.ErrMissingFile:
//do something
default:
//do something
}