登录
首页 >  Golang >  Go教程

Golang文件上传下载实现教程

时间:2026-04-09 22:59:32 156浏览 收藏

本文深入浅出地展示了如何使用Go语言标准库(net/http和os)快速实现安全可靠的文件上传与下载功能:前端通过multipart/form-data表单提交文件,后端利用r.FormFile解析并io.Copy保存;下载则通过设置Content-Disposition响应头配合http.ServeFile触发浏览器下载,同时强调了生产环境中不可或缺的安全实践——如限制文件大小、校验真实MIME类型、重命名文件、防止路径穿越及严格目录权限控制,让看似简单的功能既健壮又安全。

Golang如何实现文件上传下载功能_Golang 文件上传下载操作示例

Go语言实现文件上传下载功能非常直观,主要依赖标准库中的 net/httpos 包。通过简单的HTTP处理函数即可完成前后端交互的文件传输操作。下面以实际示例说明如何在Golang中实现文件的上传与下载。

文件上传功能实现

文件上传通常通过表单提交,前端使用 multipart/form-data 编码方式发送文件,后端解析请求并保存到服务器指定目录。

1. 前端HTML表单示例:

<form action="/upload" method="post" enctype="multipart/form-data">
  &lt;input type=&quot;file&quot; name=&quot;file&quot; /&gt;
  <button type="submit">上传文件</button>
</form>

2. 后端处理文件上传:

在Go中使用 r.FormFile() 获取上传的文件句柄,并用 io.Copy 将内容写入本地文件。

package main

import (
    "io"
    "net/http"
    "os"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "只允许POST请求", http.StatusMethodNotAllowed)
        return
    }

    file, header, err := r.FormFile("file")
    if err != nil {
        http.Error(w, "无法获取文件", http.StatusBadRequest)
        return
    }
    defer file.Close()

    // 创建本地文件
    outFile, err := os.Create("./uploads/" + header.Filename)
    if err != nil {
        http.Error(w, "无法创建文件", http.StatusInternalServerError)
        return
    }
    defer outFile.Close()

    // 复制文件内容
    _, err = io.Copy(outFile, file)
    if err != nil {
        http.Error(w, "文件保存失败", http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("文件上传成功"))
}

func main() {
    // 确保上传目录存在
    os.MkdirAll("./uploads", os.ModePerm)

    http.HandleFunc("/upload", uploadHandler)
    http.Handle("/", http.FileServer(http.Dir("."))) // 提供HTML页面
    http.ListenAndServe(":8080", nil)
}

文件下载功能实现

文件下载是通过设置响应头告知浏览器以附件形式处理,并将本地文件内容输出到响应体。

实现步骤:

  • 检查请求的文件是否存在
  • 设置 Content-Disposition 头部指定下载文件名
  • 设置 Content-Type 为 application/octet-stream
  • 使用 http.ServeFile 直接输出文件内容
func downloadHandler(w http.ResponseWriter, r *http.Request) {
    filename := r.URL.Query().Get("file")
    if filename == "" {
        http.Error(w, "缺少文件名参数", http.StatusBadRequest)
        return
    }

    filepath := "./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)
}

注册路由:

http.HandleFunc("/download", downloadHandler)

访问 /download?file=test.txt 即可触发文件下载。

安全与优化建议

在生产环境中使用时,需注意以下几点:

  • 限制上传文件大小:使用 r.ParseMultipartForm(maxSize) 防止内存溢出
  • 校验文件类型:通过 magic number 判断真实MIME类型,避免伪造扩展名
  • 重命名上传文件:防止路径穿越或覆盖关键文件
  • 设置权限:上传目录禁止执行权限,防止恶意脚本运行

总结

Go通过 net/http 提供了简洁高效的文件上传下载支持。核心在于正确处理 multipart 请求和响应头设置。配合基础的文件操作,即可快速搭建可靠的文件服务。基本上就这些,不复杂但容易忽略细节。

以上就是《Golang文件上传下载实现教程》的详细内容,更多关于的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>