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

在Golang中实现文件上传和下载功能并不复杂,借助标准库中的 net/http 包即可轻松完成。下面是一个完整的示例,包含前端HTML表单、后端文件上传处理和文件下载接口。
实现文件上传需要一个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))
}
<pre class="brush:php;toolbar:false;"><form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">上传文件</button>
</form>
实现文件下载的关键是设置正确的响应头,告知浏览器这是一个附件,应触发下载行为。使用 Content-Disposition 头来指定文件名。
后端下载处理代码:
<code>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)
}
将上传和下载处理器注册到路由,并启动服务器。
本文档主要讲述的是基于jQuery的AJAX和JSON的实例;过jQuery内置的AJAX功能,直接访问后台获得JSON格式的数据,然后通过jQuer把数据绑定到事先设计好的html模板上,直接在页面上显示。有需要的朋友可以下载看看
1
立即学习“go语言免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">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 文件,内容包含前面的上传表单。
基本上就这些。这个示例展示了如何用原生Go实现基本的文件上传下载功能,无需第三方框架也能快速搭建实用服务。
以上就是Golang文件上传下载功能实现示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号