The first is the upload page upload.html:
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><title>Upload</title></Head><Body><formMethod= "POST"Action= "/upload"enctype= "Multipart/form-data">Choose an image to upload:<inputname= "image"type= "File" /><inputtype= "Submit"value= "Upload" /></form></Body></HTML>
File Upload code:
Package Mainimport ("Html/template" "io" "Log" "Net/http" "OS") const (Upload_dir= "./uploads") Func Uploadhandler (w http. Responsewriter, R*http. Request) {ifR.method = = "GET"{T, err:= Template. Parsefiles ("upload.html") ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} t.execute (W, nil)return } ifR.method = = "POST"{F, H, err:= R.formfile ("image") ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} filename:=H.filename defer f.close () T, err:= OS. Create (Upload_dir + "/" +filename)ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} defer t.close ()if_, Err: = Io. Copy (T, f); Err! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} http. Redirect (W, R,"/view?id=" +filename, http. Statusfound)}}func Viewhandler (w http. Responsewriter, R*http. Request) {imageId:= R.formvalue ("id") ImagePath:= Upload_dir + "/" +imageIdifexists: = Isexists (ImagePath);!exists {http. NotFound (W, R)return} w.header (). Set ("Content-type", "image") http. Servefile (W, R, ImagePath)}func isexists (path string) bool {_, Err:=OS. Stat (PATH)ifErr = =Nil {return true } returnOS. Isexist (Err)}func Main () {http. Handlefunc ("/view", Viewhandler) http. Handlefunc ("/upload", Uploadhandler) Err:= http. Listenandserve (": 8080", nil)ifErr! =Nil {log. Fatal ("Listenandserve:", Err. Error ())}}
Golang File Upload