首先创建HTTP服务器并设置上传路由,再通过ParseMultipartForm解析表单,使用formFile获取文件句柄,最后保存文件到服务端。

在Golang中实现文件上传功能并不复杂,主要依赖标准库中的 net/http 和 multipart/form-data 解析能力。下面介绍如何构建一个简单的HTTP服务来接收并保存上传的文件。
首先启动一个HTTP服务,监听指定端口,并为文件上传设置路由。
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/upload", uploadHandler)
fmt.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
使用 r.ParseMultipartForm() 解析表单数据,然后通过 formFile 获取上传的文件句柄。
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
return
}
// 解析 multipart 表单,最大内存 32MB
err := r.ParseMultipartForm(32 << 20)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving file", http.StatusBadRequest)
return
}
defer file.Close()
// 打印文件信息用于调试
fmt.Fprintf(w, "Uploaded File: %+v\n", handler.Filename)
fmt.Fprintf(w, "File Size: %+v bytes\n", handler.Size)
fmt.Fprintf(w, "MIME Header: %+v\n", handler.Header)
将接收到的文件内容写入服务器磁盘。使用 os.Create 创建新文件,并用 io.Copy 写入数据。
立即学习“go语言免费学习笔记(深入)”;
import "io"
import "os"
// 创建目标文件
dst, err := os.Create("./uploads/" + handler.Filename)
if err != nil {
http.Error(w, "Unable to create file", http.StatusInternalServerError)
return
}
defer dst.Close()
// 拷贝文件内容
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "File uploaded successfully: %+v\n", handler.Filename)
确保项目根目录下有 ./uploads 文件夹,否则会因路径不存在而报错。
创建一个简单的HTML页面测试上传功能:
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" required> <button type="submit">Upload</button> </form>
访问该页面并提交文件即可触发上传流程。
基本上就这些。Golang的标准库已经提供了足够支持,无需引入第三方框架即可完成基础文件上传功能。注意控制文件大小、校验类型、防止路径遍历等安全问题在生产环境中尤为重要。不过那是下一步要考虑的事。现在先让上传跑起来再说。
以上就是如何在Golang中实现文件上传功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号