golang学习之文件上传
2016-05-30 13:40
323 查看
首先是上传页面upload.html:
文件上传代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Upload</title> </head> <body> <form method="POST" action="/upload" enctype="multipart/form-data"> Choose an image to upload: <input name="image" type="file" /> <input type="submit" value="Upload" /> </form> </body> </html>
文件上传代码:
package main import ( "html/template" "io" "log" "net/http" "os" ) const ( UPLOAD_DIR = "./uploads" ) func uploadHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { t, err := template.ParseFiles("upload.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t.Execute(w, nil) return } if r.Method == "POST" { f, h, err := r.FormFile("image") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } filename := h.Filename defer f.Close() t, err := os.Create(UPLOAD_DIR + "/" + filename) if err != 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 + "/" + imageId if exists := 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) if err == nil { return true } return os.IsExist(err) } func main() { http.HandleFunc("/view", viewHandler) http.HandleFunc("/upload", uploadHandler) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } }
相关文章推荐
- 基因数据处理41之mango使用失败
- GO语言获取utc时间戳(time_t)
- django-got an unexpected keyword argument ‘maxlength’
- django中cookies和session
- GOLANG IMPORT使用入门
- goLang 如何开发 windows 窗口界面
- 基因数据处理39之mango安装记录
- Golomb 编码
- SAP ABAP收货或者货物移动(MIGO,MB11,MB1A)在保存时候的增强点
- go行读取文件
- 如何使用hugo搭建个人博客(一)
- Go语法规范点
- django views 以及restframe work views和viewsets
- django 常见页面的跳转,渲染,以及返回
- HeyWeGo第三周项目总结
- Golang适合高并发场景的原因分析
- Go语言的并发和并行
- BSOJ: 3748 【USACO 2006 March Gold】Milk Team Select产奶比赛
- Codeforces 616D Longest k-Good Segment
- poj1003Hangover