Golang通过net/http包实现文件上传下载。2. 上传需解析multipart/form-data格式,使用r.ParseMultipartForm和r.FormFile获取文件并保存。3. 下载通过设置Header和http.ServeFile发送文件。

在Golang中实现文件上传下载,主要依赖标准库中的 net/http 包。通过处理HTTP请求与响应,可以轻松构建支持文件上传和下载的Web服务。下面分别介绍如何实现这两个功能。
文件上传
文件上传通常通过HTML表单提交,使用 multipart/form-data 编码类型。Go服务端需要解析这种格式的数据以提取文件内容。
步骤说明:
- 定义一个HTTP处理函数来接收POST请求
- 调用 r.ParseMultipartForm() 解析请求体
- 使用 r.FormFile() 获取上传的文件句柄
- 将文件内容复制到目标路径
示例代码:
立即学习“go语言免费学习笔记(深入)”;
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只允许POST方法", http.StatusMethodNotAllowed)
return
}
// 解析 multipart 表单,最大内存 32MB
err := r.ParseMultipartForm(32 << 20)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "无法获取文件", http.StatusBadRequest)
return
}
defer file.Close()
// 创建本地文件用于保存
dst, err := os.Create("./uploads/" + handler.Filename)
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 上传成功", handler.Filename)
}
前端HTML表单示例:
文件下载
文件下载的核心是设置正确的响应头,告诉浏览器这是一个需要下载的文件,并提供文件内容。
关键点:
- 设置 Content-Disposition 头,指定为附件并提供文件名
- 设置 Content-Type 为 application/octet-stream 或根据实际类型设置
- 读取文件内容并写入响应体
示例代码:
立即学习“go语言免费学习笔记(深入)”;
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "缺少文件名参数", http.StatusBadRequest)
return
}
filepath := "./uploads/" + filename
// 检查文件是否存在
if _, err := os.Stat(filepath); os.IsNotExist(err) {
http.Error(w, "文件不存在", http.StatusNotFound)
return
}
// 设置响应头
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
// 发送文件
http.ServeFile(w, r, filepath)
}
你也可以使用 http.ServeFile 快速提供静态文件服务,它会自动处理范围请求、缓存等细节。
完整服务示例
将上传和下载接口注册到路由中:
func main() {
os.MkdirAll("./uploads", os.ModePerm)
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/download", downloadHandler)
// 可选:提供一个简单的上传页面
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
html := `
`
w.Write([]byte(html))
})
fmt.Println("服务器启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
基本上就这些。Go的标准库已经足够强大,无需引入第三方框架即可完成基本的文件上传下载功能。注意生产环境中应增加权限校验、文件类型限制、防重命名等安全措施。










