用go来搭建一个简单的图片上传网站
? ? ? ?提前說明一下:代碼參考了《Go語言編程》,稍有變動, 自己親自玩了一遍。
?
? ? ? ?之前玩過go web server, 現在來用go來搭建一個簡單的圖片上傳網站, 工作目錄是:~/photoweb , 而~/photoweb/uploads用來存圖片,代碼photoweb.go在~/photoweb目錄下。
? ? ? ?看服務器代碼, ~/photoweb/photoweb.go的內容為:
package mainimport ("io""os""log""net/http" )const (UPLOAD_DIR = "./uploads" )func uploadHandler(w http.ResponseWriter, r *http.Request) {if r.Method == "GET" {str := `<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>`io.WriteString(w, str)}// 處理圖片上傳if r.Method == "POST" {f, h, err := r.FormFile("image")if err != nil {http.Error(w, err.Error(),http.StatusInternalServerError)return}filename := h.Filenamedefer 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}}}func main() {http.HandleFunc("/upload", uploadHandler)err := http.ListenAndServe(":8080", nil)if err != nil {log.Fatal("ListenAndServe: ", err.Error())} }? ? ? ?在瀏覽器中執行:http://127.0.0.1:8080/upload
? ? ? ?后臺代碼進入GET分支, 給瀏覽器端返回一段html代碼,展示成html元素, 供用戶上傳圖片, 選擇圖片, 點擊Upload按鈕上傳后, 后臺代碼進入POST分支, 于是把圖片存到了~/photoweb/uploads中。實際check了一下, 該目錄下果然有此圖片。
?
? ? ? ?為了便于在瀏覽器上直接查看上傳的圖片, 可以修改下服務器代碼, 增加Redirect, 如下:
package mainimport ("io""os""log""net/http" )const (UPLOAD_DIR = "./uploads" )func uploadHandler(w http.ResponseWriter, r *http.Request) {if r.Method == "GET" {str := `<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>`io.WriteString(w, str)}// 處理圖片上傳if r.Method == "POST" {f, h, err := r.FormFile("image")if err != nil {http.Error(w, err.Error(),http.StatusInternalServerError)return}filename := h.Filenamedefer 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 isExists(path string) bool {_, err := os.Stat(path)if err == nil {return true}return os.IsExist(err) }func viewHandler(w http.ResponseWriter, r *http.Request) {imageId := r.FormValue("id")imagePath := UPLOAD_DIR + "/" + imageIdif exists := isExists(imagePath); !exists {http.NotFound(w, r)return}w.Header().Set("Content-Type", "image")http.ServeFile(w, r, imagePath) }func main() {http.HandleFunc("/view", viewHandler)http.HandleFunc("/upload", uploadHandler)err := http.ListenAndServe(":8080", nil)if err != nil {log.Fatal("ListenAndServe: ", err.Error())} }? ? ? ?重啟服務,重新訪問http://127.0.0.1:8080/upload, 然后選擇圖片, 點擊Upload上傳, 結果在服務器對應的目錄中有該圖片, 且在瀏覽器中顯示了該圖片。
? ? ? ?如上代碼很簡單, 我之前在Apatch下寫過類似的圖片上傳服務器, 道理基本相同。
?
? ? ? ?好了, 不多說。
? ? ? ??
?
總結
以上是生活随笔為你收集整理的用go来搭建一个简单的图片上传网站的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Flutter Card使用
 - 下一篇: VC驿站全套视频在线观看(B站)