GO语言实现文件上传代码分享
作者:hebedich 时间:2023-07-22 10:56:33
功能很简单,代码也很简洁,这里就不多废话了。
package main
import (
"fmt"
"io"
"net/http"
"os"
)
const (
upload_path string = "./upload/"
)
func helloHandle(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello world!")
}
//上传
func uploadHandle(w http.ResponseWriter, r *http.Request) {
//从请求当中判断方法
if r.Method == "GET" {
io.WriteString(w, "<html><head><title>我的第一个页面</title></head><body><form action='' method=\"post\" enctype=\"multipart/form-data\"><label>上传图片</label><input type=\"file\" name='file' /><br/><label><input type=\"submit\" value=\"上传图片\"/></label></form></body></html>")
} else {
//获取文件内容 要这样获取
file, head, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
//创建文件
fW, err := os.Create(upload_path + head.Filename)
if err != nil {
fmt.Println("文件创建失败")
return
}
defer fW.Close()
_, err = io.Copy(fW, file)
if err != nil {
fmt.Println("文件保存失败")
return
}
//io.WriteString(w, head.Filename+" 保存成功")
http.Redirect(w, r, "/hello", http.StatusFound)
//io.WriteString(w, head.Filename)
}
}
func main() {
//启动一个http 服务器
http.HandleFunc("/hello", helloHandle)
//上传
http.HandleFunc("/image", uploadHandle)
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("服务器启动失败")
return
}
fmt.Println("服务器启动成功")
}
以上所述就是本文的全部内容了,希望大家能够喜欢,能够对大家学习go语言有所帮助。
标签:GO,文件上传
0
投稿
猜你喜欢
MySQL在线开启或禁用GTID模式
2024-01-24 01:13:52
vue项目的创建的步骤(图文教程)
2024-05-21 10:16:29
Python实现二维有序数组查找的方法
2021-04-15 21:31:38
opencv中颜色空间转换函数cv2.cvtColor()使用
2023-03-10 18:22:38
2018年最值得一读的互联网书单
2022-04-13 20:40:37
python中range()与xrange()用法分析
2021-03-23 00:31:30
Python Socket编程之多线程聊天室
2021-03-23 21:01:02
Python使用BeautifulSoup4修改网页内容的实战记录
2023-04-10 15:59:56
Python输出指定字符串的方法
2023-07-29 15:06:02
SQL2005 大数据量检索的分页
2024-01-25 23:24:46
聊聊通过celery_one避免Celery定时任务重复执行的问题
2021-05-20 13:19:12
Python 循环语句之 while,for语句详解
2024-01-01 02:20:50
未将对象引用设置到对象的实例 (System.NullReferenceException)
2023-06-27 10:46:53
python连接mongodb集群方法详解
2021-08-26 11:45:08
python爬虫实例详解
2021-07-05 01:37:53
详解Ubuntu环境下部署Django+uwsgi+nginx总结
2021-06-15 06:23:43
python语言的优势是什么
2022-04-15 18:45:25
keras做CNN的训练误差loss的下降操作
2023-09-03 07:41:07
Golang 性能基准测试(benchmark)详解
2024-02-08 03:10:11
Python按行读取文件的简单实现方法
2023-06-14 22:55:49