博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用go来搭建一个简单的图片上传网站
阅读量:4143 次
发布时间:2019-05-25

本文共 2881 字,大约阅读时间需要 9 分钟。

       提前说明一下:代码参考了《Go语言编程》,稍有变动, 自己亲自玩了一遍。

 

       之前玩过go web server, 现在来用go来搭建一个简单的图片上传网站, 工作目录是:~/photoweb , 而~/photoweb/uploads用来存图片,代码photoweb.go在~/photoweb目录下。

       看服务器代码, ~/photoweb/photoweb.go的内容为:

package main import (	"io"	"os"	"log"	"net/http")const (	UPLOAD_DIR = "./uploads")func uploadHandler(w http.ResponseWriter, r *http.Request) {	if r.Method == "GET" {    	str := `									
Upload
Choose an image to upload:
` 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.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 } }}func main() { http.HandleFunc("/upload", uploadHandler) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) }}

       在浏览器中执行:

       后台代码进入GET分支, 给浏览器端返回一段html代码,展示成html元素, 供用户上传图片, 选择图片, 点击Upload按钮上传后, 后台代码进入POST分支, 于是把图片存到了~/photoweb/uploads中。实际check了一下, 该目录下果然有此图片。

 

       为了便于在浏览器上直接查看上传的图片, 可以修改下服务器代码, 增加Redirect, 如下:

package main import (	"io"	"os"	"log"	"net/http")const (	UPLOAD_DIR = "./uploads")func uploadHandler(w http.ResponseWriter, r *http.Request) {	if r.Method == "GET" {    	str := `									
Upload
Choose an image to upload:
` 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.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 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 + "/" + imageId if 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()) }}

       重启服务,重新访问, 然后选择图片, 点击Upload上传, 结果在服务器对应的目录中有该图片, 且在浏览器中显示了该图片。

       如上代码很简单, 我之前在Apatch下写过类似的图片上传服务器, 道理基本相同。

 

       好了, 不多说。

        

 

转载地址:http://pizti.baihongyu.com/

你可能感兴趣的文章
keras,在 fit 和 evaluate 中 都有 verbose 这个参数标记是否打印进度条
查看>>
tensorflow2.0中valid_data的作用是在训练的过程对对比训练数据与测试数据的准确率 损失率,便于判断模型的训练效果:是过拟合还是欠拟合(过拟合)
查看>>
opencv2安装报错no module named cv2
查看>>
配分函数讲解到位的
查看>>
plt.scatter参数详解 s=25代表点的面积
查看>>
pandas.series的数据定位为什么用两个左中括号[[
查看>>
numpy常用函数之random.normal函数
查看>>
unsupported operand type(s) for + NoneType and int
查看>>
计算 sigmoid 函数的导数
查看>>
keras使用总结
查看>>
过拟合曲线与早期停止法
查看>>
ndarray维度认识及np.concatenate函数详解
查看>>
keras扁平化 激活函数 避免过拟合技巧
查看>>
keras回调监控函数
查看>>
取整函数(ceil、floor、round)
查看>>
机器学习工程师 - Udacity 卷积层的维度计算
查看>>
敏感性和特异性
查看>>
接受者操作特征曲线ROC
查看>>
参考文献的引用的格式
查看>>
pytorch 报错No module named torch
查看>>