文件上传通过HTML表单和net/http包实现,后端用ParseMultipartForm解析文件并保存;2. 下载功能通过设置Header和io.Copy发送文件流。

在Golang中实现文件上传和下载功能并不复杂,借助标准库中的 net/http 包即可轻松完成。下面是一个完整的示例,包含前端HTML表单、后端文件上传处理和文件下载接口。
1. 文件上传功能
实现文件上传需要一个HTML表单用于选择文件,并通过HTTP POST请求将文件发送到后端。后端使用 http.Request 的 ParseMultipartForm 方法解析上传的文件。
后端上传处理代码:
package main
import (
"io"
"net/http"
"os"
"path/filepath"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只允许POST请求", http.StatusMethodNotAllowed)
return
}
// 解析 multipart 表单,限制大小为 10MB
err := r.ParseMultipartForm(10 << 20)
if err != nil {
http.Error(w, "文件过大或解析失败", http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "获取文件失败", http.StatusBadRequest)
return
}
defer file.Close()
// 创建上传目录
uploadDir := "./uploads"
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
os.Mkdir(uploadDir, 0755)
}
// 构建保存路径
filePath := filepath.Join(uploadDir, handler.Filename)
dst, err := os.Create(filePath)
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
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("文件上传成功: " + handler.Filename))
}
前端HTML表单:
2. 文件下载功能
实现文件下载的关键是设置正确的响应头,告知浏览器这是一个附件,应触发下载行为。使用 Content-Disposition 头来指定文件名。
后端下载处理代码:
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "缺少文件名参数", http.StatusBadRequest)
return
}
filePath := filepath.Join("./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)
}
3. 启动HTTP服务
将上传和下载处理器注册到路由,并启动服务器。
部分功能简介:商品收藏夹功能热门商品最新商品分级价格功能自选风格打印结算页面内部短信箱商品评论增加上一商品,下一商品功能增强商家提示功能友情链接用户在线统计用户来访统计用户来访信息用户积分功能广告设置用户组分类邮件系统后台实现更新用户数据系统图片设置模板管理CSS风格管理申诉内容过滤功能用户注册过滤特征字符IP库管理及来访限制及管理压缩,恢复,备份数据库功能上传文件管理商品类别管理商品添加/修改/
立即学习“go语言免费学习笔记(深入)”;
func main() {
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/download", downloadHandler)
// 提供静态页面(可选)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
println("服务器运行在 :8080")
http.ListenAndServe(":8080", nil)
}
确保项目根目录下有 index.html 文件,内容包含前面的上传表单。
4. 安全与优化建议
- 校验文件类型(如只允许图片或PDF)
- 限制文件大小,防止恶意上传
- 对上传文件重命名,避免路径穿越攻击
- 使用UUID或时间戳作为文件名,防止冲突
- 添加身份验证中间件保护接口
基本上就这些。这个示例展示了如何用原生Go实现基本的文件上传下载功能,无需第三方框架也能快速搭建实用服务。









