用go gin server来做文件上传服务

作者:stpeace 时间:2024-05-29 22:09:12 

之前已经go get安装了gin, 现在来玩下用go gin server作图片上传服务, 代码目录如下:


taoge:~/test_gin$ tree
.
|-- public
|-- template
|  `-- select_file.html
`-- test_gin_server.go
2 directories, 2 files
taoge:~/test_gin$

test_gin_server.go内容:


package main
import (
 "fmt"
 "io"
 "log"
 "net/http"
 "os"
 "github.com/gin-gonic/gin"
)
func upload(c *gin.Context) {
 file, header, err := c.Request.FormFile("file")
 if err != nil {
   c.String(http.StatusBadRequest, fmt.Sprintf("file err : %s", err.Error()))
   return
 }
 filename := header.Filename
 out, err := os.Create("public/" + filename)
 if err != nil {
   log.Fatal(err)
 }
 defer out.Close()
 _, err = io.Copy(out, file)
 if err != nil {
   log.Fatal(err)
 }
 filepath := "http://localhost:8080/file/" + filename
 c.JSON(http.StatusOK, gin.H{"filepath": filepath})
}
func main() {
 router := gin.Default()
 router.LoadHTMLGlob("template/*")
 router.GET("/", func(c *gin.Context) {
   c.HTML(http.StatusOK, "select_file.html", gin.H{})
 })
 router.POST("/upload", upload)
 router.StaticFS("/file", http.Dir("public"))
 router.Run(":8080")
}

select_file.html的内容为:


<html>
<body>
 <form action="http://localhost:8080/upload/" enctype="multipart/form-data" method="POST">
   <input type="file" name="file" id="pic" accept="*" />
   <button type="submit">提交</button>
 </form>
</body>
</html>

go run test_gin_server.go跑起来, 在浏览器上执行:http://localhost:8080/ ,然后就出现了图片上传的页面,于是就可以上传图片了, 玩了一下, OK,服务端对应的public目录中有对应的图片。

不多说。

来源:https://blog.csdn.net/stpeace/article/details/82721770

标签:go,gin,server,文件上传,服务
0
投稿

猜你喜欢

  • python实现按首字母分类查找功能

    2023-10-13 11:05:09
  • 帮助你分析MySQL的数据类型以及建库策略

    2009-02-23 17:39:00
  • 解决vue this.$forceUpdate() 处理页面刷新问题(v-for循环值刷新等)

    2024-06-05 09:15:26
  • MySQL聚焦Web 2.0可扩展性

    2012-01-05 19:02:19
  • Python中lru_cache的使用和实现详解

    2022-04-22 10:48:28
  • 如何实现表单提交时提示正在发送

    2008-12-23 13:30:00
  • 浅谈node的事件机制

    2024-05-05 09:22:03
  • python tornado开启多进程的几种方法

    2021-09-18 22:28:17
  • python中argparse模块用法实例详解

    2022-01-09 23:34:40
  • 在ASP中使用SQL语句之11:记录统计

    2007-08-11 13:27:00
  • python break和continue用法对比

    2021-11-03 14:36:20
  • Python多继承原理与用法示例

    2023-10-22 21:01:41
  • 使用sklearn进行对数据标准化、归一化以及将数据还原的方法

    2022-03-28 19:44:27
  • Python调用shell命令常用方法(4种)

    2021-05-06 08:22:06
  • python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析

    2022-12-17 22:26:30
  • python控制nao机器人身体动作实例详解

    2023-08-26 11:33:17
  • vs code开发中语法正确但显示报错问题分析解决

    2023-08-05 11:54:26
  • Python3访问并下载网页内容的方法

    2022-11-12 06:08:39
  • python删除列表中特定元素的几种方法

    2023-12-21 02:17:12
  • Pytorch框架之one_hot编码函数解读

    2023-02-16 11:34:05
  • asp之家 网络编程 m.aspxhome.com