答案:Golang通过net/http和os库实现文件上传下载。上传时解析multipart/form-data,保存文件至服务器;下载时设置响应头触发浏览器下载,安全措施包括验证文件类型、限制大小、重命名、鉴权及缓冲读写。

在Golang中实现文件上传与下载功能并不复杂,主要依赖标准库net/http和os。通过合理处理HTTP请求与响应,可以轻松构建安全高效的文件传输服务。
文件上传通常通过HTML表单提交,后端使用http.Request解析multipart/form-data格式的数据。
关键步骤:
request.ParseMultipartForm(maxMemory)解析表单数据- 调用request.FormFile("file")获取上传的文件句柄- 使用io.Copy将文件内容写入服务器本地路径- 返回上传结果给客户端
示例代码:
立即学习“go语言免费学习笔记(深入)”;
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "仅支持POST请求", http.StatusMethodNotAllowed)
return
}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 解析表单,限制内存使用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.Write([]byte("文件上传成功"))}
文件下载的核心是设置正确的响应头,并将文件内容写入响应体。
关键点:
os.Open打开目标文件- 设置Content-Disposition头以触发浏览器下载- 设置Content-Type为application/octet-stream- 使用io.Copy将文件流写入响应
示例代码:
立即学习“go语言免费学习笔记(深入)”;
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "缺少文件名参数", http.StatusBadRequest)
return
}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">filepath := "./uploads/" + filename
file, err := os.Open(filepath)
if err != nil {
http.Error(w, "文件不存在", http.StatusNotFound)
return
}
defer file.Close()
// 获取文件信息
fileInfo, _ := file.Stat()
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
// 发送文件
_, err = io.Copy(w, file)
if err != nil {
http.Error(w, "发送文件失败", http.StatusInternalServerError)
return
}}
实际项目中需考虑安全性与稳定性。
基本上就这些。只要掌握HTTP协议的基本交互方式,结合Go语言简洁的IO操作,就能快速实现稳定的文件上传下载功能。注意边界情况处理和安全防护,才能用于生产环境。
以上就是Golang如何实现文件上传与下载功能_Golang Web文件上传下载实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号