使用Go标准库net/http实现文件上传,通过ParseMultipartForm解析表单,FormFile获取文件句柄,保存到服务器指定目录,同时支持前端HTML表单提交,完整示例包含错误处理与文件路径安全校验。

实现一个文件上传接口在Go语言中非常直接,利用标准库
net/http
使用
http.Request
ParseMultipartForm
request.FormFile
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
// 上传文件处理函数
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// 只允许 POST 方法
if r.Method != "POST" {
http.Error(w, "只允许 POST 请求", http.StatusMethodNotAllowed)
return
}
// 解析 multipart 表单,最大内存 32MB
err := r.ParseMultipartForm(32 << 20)
if err != nil {
http.Error(w, "解析表单失败", http.StatusBadRequest)
return
}
// 获取上传的文件,字段名为 "file"
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "获取文件失败", http.StatusBadRequest)
return
}
defer file.Close()
// 创建保存文件的目录
uploadDir := "./uploads"
if err := os.MkdirAll(uploadDir, os.ModePerm); err != nil {
http.Error(w, "创建目录失败", http.StatusInternalServerError)
return
}
// 构造保存路径,防止路径穿越
filename := filepath.Base(handler.Filename)
dstPath := filepath.Join(uploadDir, filename)
// 创建目标文件
dst, err := os.Create(dstPath)
if err != nil {
http.Error(w, "创建文件失败", http.StatusInternalServerError)
return
}
defer dst.Close()
// 拷贝文件内容
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, "保存文件失败", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "文件上传成功: %s (%d bytes)", handler.Filename, handler.Size)
}
func main() {
// 注册处理函数
http.HandleFunc("/upload", uploadHandler)
// 提供静态页面用于测试(可选)
http.Handle("/", http.FileServer(http.Dir(".")))
fmt.Println("服务器启动,端口: 8080")
http.ListenAndServe(":8080", nil)
}
在项目根目录下创建一个
index.html
<!DOCTYPE html>
<html>
<head>
<title>文件上传测试</title>
</head>
<body>
<h2>上传文件</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">上传</button>
</form>
</body>
</html>
实际项目中需注意以下几点:
立即学习“go语言免费学习笔记(深入)”;
ParseMultipartForm
filepath.Base
http.Server
将上面的 Go 代码保存为
main.go
index.html
go run main.go
访问
http://localhost:8080
基本上就这些。不复杂但容易忽略细节,尤其是安全方面。按需扩展即可。
以上就是GolangHTTP文件上传接口实现示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号