首先实现文件上传与下载功能,通过net/http解析multipart表单获取文件并保存;其次设置响应头触发浏览器下载,防止路径穿越;最后通过限制大小、校验类型、使用随机命名等措施保障安全。

实现文件上传与下载功能在Golang中非常常见,尤其在构建Web服务时。通过标准库
net/http
os
文件上传的核心是解析HTTP请求中的multipart/form-data数据,提取上传的文件并保存到服务器指定目录。
关键步骤包括:
http.Request
ParseMultipartForm
FormFile
os.Create
io.Copy
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "仅支持POST请求", http.StatusMethodNotAllowed)
return
}
// 解析multipart表单,最大内存10MB
r.ParseMultipartForm(10 << 20)
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()
// 复制文件内容
io.Copy(dst, file)
fmt.Fprintf(w, "文件 %s 上传成功", handler.Filename)
}文件下载的关键是设置正确的响应头,让浏览器触发下载行为,而不是直接显示内容。
立即学习“go语言免费学习笔记(深入)”;
主要操作包括:
os.Open
Content-Disposition
Content-Type
application/octet-stream
http.ServeContent
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "缺少文件名参数", http.StatusBadRequest)
return
}
// 简单路径安全检查
if strings.Contains(filename, "..") || strings.Contains(filename, "/") {
http.Error(w, "非法文件名", http.StatusBadRequest)
return
}
path := "./uploads/" + filename
file, err := os.Open(path)
if err != nil {
http.Error(w, "文件不存在", http.StatusNotFound)
return
}
defer file.Close()
// 设置响应头
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeContent(w, r, filename, time.Now(), file)
}在生产环境中,需额外考虑安全性与性能:
以上就是Golang文件上传与下载功能实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号