教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 使用 golang的gin框架实现,文件上传

使用 golang的gin框架实现,文件上传

发布时间:2022-01-08   编辑:jiaochengji.com
教程集为您提供使用 golang的gin框架实现,文件上传等资源,欢迎您收藏本站,我们将为您提供最新的使用 golang的gin框架实现,文件上传资源

一、引入 gin 框架

<pre><code>import "ginhub.com/gin-gonic/gin</code></pre>

二、渲染页面

<pre><code>router := gin.Default() router.LoadHTMLGlob("view/*") router.GET("/upload",func(c *gin.Context) { c.HTML(http.StatusOK,"upload.tmpl",gin.H{}) })</code></pre>

三、处理上传文件

<pre><code>router.POST("/upload", func(c *gin.Context) { // Source file, err := c.FormFile("file") if err != nil { c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error())) return } basePath := "./upload/" filename := basePath filepath.Base(file.Filename) if err := c.SaveUploadedFile(file, filename); err != nil { c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error())) return } c.String(http.StatusOK,fmt.Sprintf("文件 %s 上传成功 ", file.Filename)) })</code></pre>

全部代码:

<pre><code>package main import ( "github.com/gin-gonic/gin" "net/http" "fmt" "path/filepath" ) func main() { router := gin.Default() router.LoadHTMLGlob("view/*") router.GET("/upload",func(c *gin.Context) { c.HTML(http.StatusOK,"upload.tmpl",gin.H{}) }) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { file, err := c.FormFile("file") if err != nil { c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error())) return } basePath := "./upload/" filename := basePath filepath.Base(file.Filename) if err := c.SaveUploadedFile(file, filename); err != nil { c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error())) return } c.String(http.StatusOK,fmt.Sprintf("文件 %s 上传成功 ", file.Filename)) }) router.Run(":8080") }</code></pre>

文档链接:https://github.com/gin-gonic/...

到此这篇关于“使用 golang的gin框架实现,文件上传”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
使用 golang的gin框架实现,文件上传
Gin 框架绑定 JSON 参数使用 jsoniter
golang 上传文件(包括 gin 实现)
想系统学习GO语言(Golang
Golang Gin 实战(六)| 获取Form表单参数和原理分析
gin框架502错误
Golang pprof 性能分析与火焰图
Go 语言进阶教程
项目结构设置
使用 Go 创建项目

[关闭]
~ ~