github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/web/examples/multipart.go (about) 1 // Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build ingore 6 7 package main 8 9 import ( 10 "bytes" 11 "crypto/md5" 12 "fmt" 13 "io" 14 15 "github.com/chai2010/gopkg/web" 16 ) 17 18 func Md5(r io.Reader) string { 19 hash := md5.New() 20 io.Copy(hash, r) 21 return fmt.Sprintf("%x", hash.Sum(nil)) 22 } 23 24 func index() string { return page } 25 26 func multipart(ctx *web.Context) string { 27 ctx.Request.ParseMultipartForm(10 * 1024 * 1024) 28 form := ctx.Request.MultipartForm 29 var output bytes.Buffer 30 output.WriteString("<p>input1: " + form.Value["input1"][0] + "</p>") 31 output.WriteString("<p>input2: " + form.Value["input2"][0] + "</p>") 32 33 fileHeader := form.File["file"][0] 34 filename := fileHeader.Filename 35 file, err := fileHeader.Open() 36 if err != nil { 37 return err.Error() 38 } 39 40 output.WriteString("<p>file: " + filename + " " + Md5(file) + "</p>") 41 return output.String() 42 } 43 44 func main() { 45 web.Get("/", index) 46 web.Post("/multipart", multipart) 47 web.Run("0.0.0.0:9999") 48 } 49 50 const page = ` 51 <html> 52 <head><title>Multipart Test</title></head> 53 <body> 54 <form action="/multipart" enctype="multipart/form-data" method="POST"> 55 <label for="file"> Please select a File </label> 56 <input id="file" type="file" name="file"/> 57 <br> 58 <label for="input1"> Please write some text </label> 59 <input id="input1" type="text" name="input1"/> 60 <br> 61 <label for="input2"> Please write some more text </label> 62 <input id="input2" type="text" name="input2"/> 63 <br> 64 <input type="submit" name="Submit" value="Submit"/> 65 </form> 66 </body> 67 </html> 68 `