Yes, I have found answers:
http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
golang POST data using the Content-Type multipart/form-data
HTTP-POST file multipart programming in Go language
And answers not helpful, because I'm get error with multipart.NewWriter. My version of go lang 1.3.3
I'm trying to send some text data and image with form(templates/form.html)
<form enctype="multipart/form-data" method="POST">
<div class="row">
<div class="large-6 columns">
<label>Image
<input type="file" name="Image" class="button"/>
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>About Me
<textarea type="text" name="aboutMySelf" class="aboutMySelf"></textarea>
</label>
</div>
</div>
</form>
And my Go approach is like this:
package main
import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/textproto"
"os"
"reflect"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
)
func render(w http.ResponseWriter, tmpl string, context map[string]interface{}) {
tmpl_list := []string{fmt.Sprintf("templates/%s.html", tmpl)}
t, err := template.ParseFiles(tmpl_list...)
if err != nil {
log.Print("template parsing error: ", err)
}
err = t.Execute(w, context)
if err != nil {
log.Print("template executing error: ", err)
}
}
type FileHeader struct {
Filename string
Header textproto.MIMEHeader
// contains filtered or unexported fields
}
func uploadImage(q *http.Request, nameInForm string) {
q.ParseMultipartForm(32 << 20)
file, _, err := q.FormFile(nameInForm)
if err != nil {
fmt.Println(err)
}
defer file.Close()
f, err := os.OpenFile("./static/uploadimages/"+handler.Filename+".jpg", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
}
defer f.Close()
io.Copy(f, file)
}
func main() {
rtr := mux.NewRouter()
//ADMIN SECTION
rtr.HandleFunc("/myself", myself).Methods("GET")
rtr.HandleFunc("/myself", myselfP).Methods("POST")
rtr.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
http.Handle("/", rtr)
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
func myself(w http.ResponseWriter, q *http.Request) {
render(w,"form",nil)
}
func myselfP(w http.ResponseWriter, q *http.Request) {
err := q.ParseForm()
if err != nil {
// Handle error
fmt.Println(err)
}
uploadImage(q, "Image")
http.Redirect(w, q, "/myself", http.StatusFound)
}
File uploads perfectly, but I cann't get data from textarea. I'm trying understand what different between simple form with fields and multipart form, and how I can get data from fields
Thanks and regards