Go实现图片上传

来源:互联网 发布:nginx 在线人数统计 编辑:程序博客网 时间:2024/06/01 08:38

先写个大概的前端页面:

 <div class="result-title">                <h1>上传图片</h1>            </div>            <div class="result-content">                <form method="POST" action="/gallery" enctype="multipart/form-data">                    <h2>选择一张图片上传</h2>                    <input name="image" type="file">                    <input type="submit" value="上传">                </form>            </div>

接着是服务端代码:

//照片管理func gallery(w http.ResponseWriter, r *http.Request){    //前面这些是我用于判断用户登录用的cookies    cookieskey := "xulogin"+r.Host    cookieskey = strings.Replace(cookieskey,".","z",-1)    cookieskey = strings.Replace(cookieskey,":","x",-1)    cookie, err := r.Cookie(cookieskey)    if err != nil || cookie.Value == "" || cookies.CookiesMap[cookieskey].Cookievalue == "" || cookies.CookiesMap[cookieskey].Cookievalue != cookie.Value{        http.Redirect(w, r, "/login", http.StatusFound)        return    }else if cookies.CookiesMap[cookieskey].Cookievalue != "" && cookies.CookiesMap[cookieskey].Cookievalue == cookie.Value{        if r.Method == "GET"{            //如果是GET请求,往浏览器发送模板gallery.html,也就是前面写的前端页面            t, _ := template.ParseFiles("static/admin/gallery.html")            t.Execute(w, nil)        }        //在用户上传完图片点提交后,会向服务端发送POST请求,然后就执行下面的代码        if r.Method == "POST"{            //设置上传路径            UploadPath := "./static/images"            //获取名为image的文件            file, handler, err := r.FormFile("image")              if err != nil {                  http.Error(w, err.Error(), http.StatusInternalServerError)                  return              }              filename := handler.Filename              defer file.Close()              //创建文件            t, err := os.Create(UploadPath + "/" + filename)              if err != nil {                  http.Error(w, err.Error(), http.StatusInternalServerError)                  return              }              defer t.Close()              //将上传的文件拷贝至所创建的文件中            if _, err := io.Copy(t, file); err != nil {                  http.Error(w, err.Error(), http.StatusInternalServerError)                  return              }              io.WriteString(w, "Upload Success!")        }    }}
0 0
原创粉丝点击