答案是使用Golang标准库可快速实现文件上传下载。1. 创建main.go和uploads目录;2. 用net/http处理请求,ParseMultipartForm解析文件,io.Copy保存至uploads;3. 提供下载接口通过http.ServeFile返回文件。

用Golang构建一个简单的文件上传下载服务并不复杂,主要依赖标准库中的 net/http 和文件操作功能。下面是一个完整示例,包含文件上传接口和文件下载接口,适合快速搭建本地测试服务或轻量级文件服务。
使用 http.Request 的 ParseMultipartForm 方法解析上传的文件,然后通过 io.Copy 将内容保存到服务器本地。
代码片段:func uploadFile(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()
// 创建本地文件
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 上传成功\n", handler.Filename)
}通过指定文件名从 uploads/ 目录读取文件,并设置适当的响应头实现浏览器下载。
代码片段:func downloadFile(w http.ResponseWriter, r *http.Request) {
filename := strings.TrimPrefix(r.URL.Path, "/download/")
filepath := "uploads/" + filename
// 检查文件是否存在
if _, err := os.Stat(filepath); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
// 设置响应头触发下载
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
// 发送文件
http.ServeFile(w, r, filepath)
}在 main 函数中注册处理函数,并启动服务器。
立即学习“go语言免费学习笔记(深入)”;
完整 main 函数示例:package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
// 确保 uploads 目录存在
os.MkdirAll("uploads", os.ModePerm)
// 路由
http.HandleFunc("/upload", uploadFile)
http.HandleFunc("/download/", downloadFile)
// 提供一个简单页面用于上传测试
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
html := `
<html>
<body>
<h3>上传文件</h3>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
</body>
</html>
`
w.Write([]byte(html))
})
fmt.Println("服务启动,地址:http://localhost:8080")
http.ListenAndServe(":8080", nil)
}运行后访问 http://localhost:8080 即可看到上传页面,上传的文件保存在 uploads/ 目录下,可通过 /download/filename 下载对应文件。
基本上就这些,不复杂但容易忽略安全检查和路径过滤。生产环境建议增加文件类型限制、大小控制、防覆盖机制和身份验证。不过作为学习或内网工具,这个例子足够用了。
以上就是Golang构建文件上传下载服务示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号