加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

go---上传下载图片

(2016-11-03 12:40:37)
标签:

it

分类: go
1、---------------------------------主类photoweb.go

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]
  Choose an image to upload : [input name=image type=file ]
  [input type=submit value=Upload ]
[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" {
 t, _ := template.ParseFiles("login.gtpl")
      t.Execute(w, nil)
}
}

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]

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有