首先是上传页面upload.html:

<!doctype html>
<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>

文件上传代码:

package main

import (
"html/template"
"io"
"log"
"net/http"
"os"
) const (
UPLOAD_DIR = "./uploads"
) func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("upload.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
t.Execute(w, nil)
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 main() {
http.HandleFunc("/view", viewHandler)
http.HandleFunc("/upload", uploadHandler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}

最新文章

  1. H-1B身份六年后的延期问题
  2. Java开发的基础条件:
  3. jdk环境配置
  4. java提高篇(二四)-----HashSet
  5. 改变Vim在iTerm2中的光标
  6. codeforces 567D.One-Dimensional Battle Ships 解题报告
  7. java继承覆盖总结
  8. Java并发编程:Java ConcurrentModificationException异常原因和解决方法
  9. CSS属性(常用的属性)
  10. asp.net MVC EF Where 过滤条件怎么写
  11. java与数据结构(4)---java实现双向循环链表
  12. IP相关常识
  13. POJ-1287 Networking---裸的不能再裸的MST
  14. 单向链表的Java实现
  15. body里面的onload和window.onload,window.load的区别
  16. WPF系列(1)WPF和XAML基础
  17. 关于for,while,dowhile效率测试
  18. Mysql 隐式转换
  19. zabbix之运维疑难总结
  20. 【转】如何解决使用keil下载或者调试程序是提示的“Invalid ROM Table”信息!

热门文章

  1. QTP如何准确识别Dialog中的对象
  2. ie8在win7系统下怎么安装或重装?[转载]
  3. Arch下error: signature from &quot;NAME&lt;EMAIL ADD&gt;&quot;
  4. 算法 PK 猫咪 | 章鱼保罗后继竟然是只猫?
  5. Intellig IDEA 搭建spring boot 热部署
  6. MD5算法分析
  7. 为 JSON 字符串创建对象
  8. 前端之JS的线程(最易懂)
  9. poi操作Excel并修改单元格背景色
  10. 1、The Fctory Pattern(工厂模式:解决对象创建问题)