Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Golang文件上传下载功能实现示例_创想鸟

Golang文件上传下载功能实现示例

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

golang文件上传下载功能实现示例

在Golang中实现文件上传和下载功能并不复杂,借助标准库中的 net/http 包即可轻松完成。下面是一个完整的示例,包含前端HTML表单、后端文件上传处理和文件下载接口。

1. 文件上传功能

实现文件上传需要一个HTML表单用于选择文件,并通过HTTP POST请求将文件发送到后端。后端使用 http.Request 的 ParseMultipartForm 方法解析上传的文件。

后端上传处理代码:

package mainimport (    "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))}

前端HTML表单:

        

2. 文件下载功能

实现文件下载的关键是设置正确的响应头,告知浏览器这是一个附件,应触发下载行为。使用 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 := 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)}

3. 启动HTTP服务

将上传和下载处理器注册到路由,并启动服务器。

基于jQuery的AJAX和JSON的实例 中文WORD版 基于jQuery的AJAX和JSON的实例 中文WORD版

本文档主要讲述的是基于jQuery的AJAX和JSON的实例;过jQuery内置的AJAX功能,直接访问后台获得JSON格式的数据,然后通过jQuer把数据绑定到事先设计好的html模板上,直接在页面上显示。有需要的朋友可以下载看看

基于jQuery的AJAX和JSON的实例 中文WORD版 1 查看详情 基于jQuery的AJAX和JSON的实例 中文WORD版

立即学习“go语言免费学习笔记(深入)”;

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 文件,内容包含前面的上传表单。

4. 安全与优化建议

校验文件类型(如只允许图片或PDF) 限制文件大小,防止恶意上传 对上传文件重命名,避免路径穿越攻击 使用UUID或时间戳作为文件名,防止冲突 添加身份验证中间件保护接口

基本上就这些。这个示例展示了如何用原生Go实现基本的文件上传下载功能,无需第三方框架也能快速搭建实用服务。

以上就是Golang文件上传下载功能实现示例的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1141535.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
《卡拉彼丘》×《Pop子与Pipi美》联动开启,大头玩法、联动皮肤激萌上线!
上一篇 2025年12月2日 18:40:36
2024年末冲业绩?《诛仙世界》《燕云十六声》等大作扎堆公测
下一篇 2025年12月2日 18:40:46

相关推荐

发表回复

登录后才能评论
关注微信