golang学习之文件上传
2024-10-20 03:22:34
首先是上传页面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())
}
}
最新文章
- H-1B身份六年后的延期问题
- Java开发的基础条件:
- jdk环境配置
- java提高篇(二四)-----HashSet
- 改变Vim在iTerm2中的光标
- codeforces 567D.One-Dimensional Battle Ships 解题报告
- java继承覆盖总结
- Java并发编程:Java ConcurrentModificationException异常原因和解决方法
- CSS属性(常用的属性)
- asp.net MVC EF Where 过滤条件怎么写
- java与数据结构(4)---java实现双向循环链表
- IP相关常识
- POJ-1287 Networking---裸的不能再裸的MST
- 单向链表的Java实现
- body里面的onload和window.onload,window.load的区别
- WPF系列(1)WPF和XAML基础
- 关于for,while,dowhile效率测试
- Mysql 隐式转换
- zabbix之运维疑难总结
- 【转】如何解决使用keil下载或者调试程序是提示的“Invalid ROM Table”信息!
热门文章
- QTP如何准确识别Dialog中的对象
- ie8在win7系统下怎么安装或重装?[转载]
- Arch下error: signature from ";NAME<;EMAIL ADD>;";
- 算法 PK 猫咪 | 章鱼保罗后继竟然是只猫?
- Intellig IDEA 搭建spring boot 热部署
- MD5算法分析
- 为 JSON 字符串创建对象
- 前端之JS的线程(最易懂)
- poi操作Excel并修改单元格背景色
- 1、The Fctory Pattern(工厂模式:解决对象创建问题)