您的位置:首页 >Golang实现文件上传下载功能详解
发布于2025-12-11 阅读(0)
扫一扫,手机访问
Golang通过net/http包实现文件上传下载,上传使用ParseMultipartForm解析表单,保存文件至指定目录;下载设置Content-Disposition响应头触发浏览器下载,同时需校验文件存在性。前端通过multipart/form-data提交文件,服务端处理并返回结果,结合安全措施如文件名重命名、类型检查、大小限制和权限控制,可构建稳定可靠的文件传输功能。

在Golang中实现文件上传和下载功能并不复杂,主要依赖标准库中的 net/http 包。通过合理设计HTTP处理器,可以轻松支持客户端上传文件到服务器,以及从服务器下载文件。
文件上传通常使用HTTP的POST请求,客户端通过表单提交文件。服务端需要解析 multipart/form-data 格式的数据。
以下是一个简单的文件上传处理示例:
package mainimport ( "io" "log" "net/http" "os" )
func uploadHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "只允许POST方法", http.StatusMethodNotAllowed) return }
// 解析上传的文件(限制内存中最多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() // 创建本地文件用于保存 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 } w.WriteHeader(http.StatusOK) w.Write([]byte("文件上传成功: " + handler.Filename))}
func main() { // 确保上传目录存在 os.MkdirAll("./uploads", os.ModePerm)
http.HandleFunc("/upload", uploadHandler) http.Handle("/", http.FileServer(http.Dir("./static/"))) // 提供静态页面 log.Println("服务器启动,监听 :8080") log.Fatal(http.ListenAndServe(":8080", nil))}
上面代码中,r.FormFile("file") 获取前端表单中 name="file" 的文件字段。上传的文件被保存在 ./uploads 目录下。
文件下载的核心是设置正确的响应头,告知浏览器这是一个需要下载的文件,而不是直接显示。
可以通过设置 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 := "./uploads/" + filename
// 检查文件是否存在
_, err := os.Stat(filepath)
if 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.HandleFunc("/download", downloadHandler),用户访问 /download?file=example.txt 即可下载对应文件。
提供一个简单页面用于测试上传功能:
<!-- 存放在 ./static/index.html -->
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">上传文件</button>
</form>
<a href="/download?file=test.txt">下载示例文件</a>
实际项目中还需考虑以下几点:
基本上就这些。Golang标准库已经足够支撑基础的文件传输需求,无需引入额外框架即可快速实现稳定功能。
上一篇:Win10服务无法启动怎么解决?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9