首页 > Web开发 > 详细

gin上传单文件

时间:2020-01-16 20:37:23      阅读:74      评论:0      收藏:0      [点我收藏+]
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "net/http"
 6     "path/filepath"
 7 
 8     "github.com/gin-gonic/gin"
 9 )
10 
11 func main() {
12     r := gin.Default()
13     // Set a lower memory limit for multipart forms, default is 32MB
14     r.MaxMultipartMemory = 8 << 20 // 8MB
15     r.Static("/", "./public")
16     r.POST("/upload", func(c *gin.Context) {
17         name := c.PostForm("name")
18         email := c.PostForm("email")
19 
20         // Source
21         file, err := c.FormFile("file")
22         if err != nil {
23             c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
24             return
25         }
26 
27         filename := filepath.Base(file.Filename)
28         if err := c.SaveUploadedFile(file, filename); err != nil {
29             c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
30             return
31         }
32         c.String(http.StatusOK,
33             fmt.Sprintf("File %s uploaded successfully with fields name=%s and emails=%s.", file.Filename, name, email))
34     })
35     r.Run(":8080")
36 }

技术分享图片

 

技术分享图片技术分享图片

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8">
 5     <title>Single file upload</title>
 6 </head>
 7 <body>
 8 <h1>Upload single file with fields</h1>
 9 
10 <form action="/upload" method="post" enctype="multipart/form-data">
11     Name: <input type="text" name="name"><br>
12     Email: <input type="email" name="email"><br>
13     Files: <input type="file" name="file"<br><br>
14     <input type="submit" value="Submit">
15 </form>
16 </body>

技术分享图片

gin上传单文件

原文:https://www.cnblogs.com/chenguifeng/p/12203040.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!