go---上传下载图片
(2016-11-03 12:40:37)
标签:
it |
分类: go |
1、---------------------------------主类photoweb.go
Choose an image to upload : [input name=image type=file
]
[input type=submit value=Upload ]
t, _ :=
template.ParseFiles("login.gtpl")
t.Execute(w, nil)
package main
import (
"io"
"log"
"net/http"
"os"
"html/template"
)
const (
UPLOAD_DIR="./uploads"
)
func uploadHandler(w http.ResponseWriter, r
*http.Request){
if r.Method =="GET" {
io.WriteString(w,"[form
method=POST action=/upload
enctype=multipart/form-data]
[form]")
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 uploadPageHandler(w http.ResponseWriter, r
*http.Request){
if r.Method =="GET" {
}
}
func main(){
http.HandleFunc("/uploadpage",uploadPageHandler)
http.HandleFunc("/upload",uploadHandler)
http.HandleFunc("/view",viewHandler)
err := http.ListenAndServe(":8181",nil)
if err !=nil{
log.Fatal("ListenAndServe",err.Error())
}
}
--------------------------------------
2、----------------------上传页面login.gtpl
[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]
前一篇:go---json流式读写
后一篇:go--数据库操作

加载中…