使用net/http和文件操作实现图像上传;2. 创建含multipart表单的HTML页面;3. Go后端解析文件并保存;4. 支持图片展示功能。

在Golang中实现基础的图像上传与展示功能并不复杂,只需使用标准库中的 net/http 和文件操作相关功能即可完成。下面是一个简单、实用的实现方式,包含前端表单、后端接收、文件保存和图片展示。
首先,准备一个简单的HTML页面,允许用户选择并上传图片:
<form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="image" accept="image/*" required> <button type="submit">上传图片</button> </form>
注意:必须设置 enctype="multipart/form-data",否则文件无法正确提交。
在Go服务端,通过 http.Request 的 ParseMultipartForm 方法解析上传的文件:
立即学习“go语言免费学习笔记(深入)”;
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
return
}
// 解析 multipart 表单,最大内存 10MB
r.ParseMultipartForm(10 << 20)
file, handler, err := r.FormFile("image")
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()
// 将上传的文件内容复制到本地
io.Copy(dst, file)
fmt.Fprintf(w, "文件 %s 上传成功", handler.Filename)
}
确保项目根目录下有 uploads 文件夹,或在程序中动态创建:
os.MkdirAll("uploads", os.ModePerm)
要展示图片,最简单的方法是将 uploads 目录设为静态文件服务路径:
// 将 /images/ 路由指向 uploads 目录
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("uploads/"))))
// 示例访问:http://localhost:8080/images/filename.jpg
也可以提供一个页面列出所有已上传图片:
func listImages(w http.ResponseWriter, r *http.Request) {
files, _ := filepath.Glob("uploads/*")
var imageLinks string
for _, f := range files {
filename := filepath.Base(f)
imageLinks += fmt.Sprintf("<img src='/images/%s' width='200' style='margin:10px;'>", filename)
}
fmt.Fprintf(w, "<h3>已上传图片</h3>%s", imageLinks)
}
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
func main() {
os.MkdirAll("uploads", os.ModePerm)
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/images", listImages)
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("uploads/"))))
fmt.Println("服务器启动在 :8080")
http.ListenAndServe(":8080", nil)
}
运行程序后,访问 http://localhost:8080(可配合前端页面),上传图片后可通过 /images/xxx.jpg 直接访问,或访问 /images 查看所有图片缩略图。
基本上就这些。不复杂但容易忽略的是文件类型检查、重命名避免冲突、大小限制等安全措施,生产环境建议加上。当前实现适合学习和原型开发。
以上就是Golang如何开发基础的图像上传与展示功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号