登录
首页 >  Golang >  Go教程

Golang图片上传与展示实现教程

时间:2026-02-01 11:19:32 198浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Golang实现图片上传与展示教程》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

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

Golang如何开发基础的图像上传与展示功能

在Golang中实现基础的图像上传与展示功能并不复杂,只需使用标准库中的 net/http 和文件操作相关功能即可完成。下面是一个简单、实用的实现方式,包含前端表单、后端接收、文件保存和图片展示。

1. 创建图像上传表单

首先,准备一个简单的HTML页面,允许用户选择并上传图片:

<form action="/upload" method="post" enctype="multipart/form-data">
  &lt;input type=&quot;file&quot; name=&quot;image&quot; accept=&quot;image/*&quot; required&gt;
  <button type="submit">上传图片</button>
</form>

注意:必须设置 enctype="multipart/form-data",否则文件无法正确提交。

2. 处理图像上传

在Go服务端,通过 http.RequestParseMultipartForm 方法解析上传的文件:

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

    // 解析 multipart 表单,最大内存 10MB
    r.ParseMultipartForm(10 

确保项目根目录下有 uploads 文件夹,或在程序中动态创建:

os.MkdirAll("uploads", os.ModePerm)

3. 展示已上传的图片

要展示图片,最简单的方法是将 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)
}

4. 完整主函数示例

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图片上传与展示实现教程》的详细内容,更多关于的资料请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>