package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/upload", upload)
http.ListenAndServe(":1789", nil)
}
func upload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintln(w, "upload ok!")
}
func index(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(tpl))
}
const tpl = `<html>
<head>
<title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{...{.}...}"/>
<input type="submit" value="upload" />
</form>
</body>
</html>`
Golang实现http文件上传小功能
最新推荐文章于 2025-11-09 14:01:49 发布
本文介绍了一个使用Go语言编写的简单HTTP服务器,该服务器支持基本的文件上传功能。通过解析multipart表单数据,服务器能够接收上传的文件,并将其保存到指定的位置。此外,还提供了一个简单的HTML表单用于选择和上传文件。
1120

被折叠的 条评论
为什么被折叠?



