I have a html page that has the follow code.
<form action="/image" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
I then have some Go code to get the file on the back end.
func uploaderHandler(w http.ResponseWriter, r *http.Request) {
userInput := r.FormValue("file")
but anytime I try to use userInput from the go script, it returns nothing. Am I passing the variables wrong?
EDIT: I know how to upload things to golang that are text/passwords. I am having trouble uploading images to Go with the code.
EDIT 2: Read the Go guide a found the solution. See below.
First you need to use req.FormFile
not FormValue
, then you will have to manually save the image to a file.
Something like this:
func HandleUpload(w http.ResponseWriter, req *http.Request) {
in, header, err := req.FormFile("file")
if err != nil {
//handle error
}
defer in.Close()
//you probably want to make sure header.Filename is unique and
// use filepath.Join to put it somewhere else.
out, err := os.OpenFile(header.Filename, os.O_WRONLY, 0644)
if err != nil {
//handle error
}
defer out.Close()
io.Copy(out, in)
//do other stuff
}