gin系列-文件上传
程序员文章站
2022-03-25 17:02:56
单文件上传 前端 后端 后端 ......
单文件上传
前端
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>文件上传</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> //upload跳转控制 <input type="file" name="f1"> //和c.formfile一致 <input type="submit" value="上传"> </form> </body> </html>
后端
#main.go package main import ( "github.com/gin-gonic/gin" "net/http" "path" ) func main() { r := gin.default() //处理multipart forms提交文件时默认的内存限制是32 mib r.maxmultipartmemory = 8 //router.maxmultipartmemory = 8 << 20 // 8 mib r.loadhtmlfiles("./index.html") r.get("/index", func(c *gin.context) { c.html(http.statusok,"index.html",nil) }) r.post("/upload", func(c *gin.context) { //从请求中读取文件 f, err := c.formfile("f1") //和从请求中获取携带的参数一样 if err != nil { c.json(http.statusbadrequest, gin.h{ "error": err.error(), }) }else { //将读取到的文件保存到本地(服务端) //dst := fmt.sprintf("./%s", f.filename) dst := path.join("./", f.filename) _ = c.saveuploadedfile(f,dst) c.json(http.statusok, gin.h{ "status":"ok", }) } }) r.run(":9090") }
多文件上传
前端
#index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>文件上传</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1"> <input type="file" name="f1"> <input type="submit" value="上传"> </form> </body> </html>
后端
#main.go package main import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" "path" ) func main() { r := gin.default() //处理multipart forms提交文件时默认的内存限制是32 mib r.maxmultipartmemory = 8 //router.maxmultipartmemory = 8 << 20 // 8 mib r.loadhtmlfiles("./index.html") r.get("/index", func(c *gin.context) { c.html(http.statusok,"index.html",nil) }) r.post("/upload", func(c *gin.context) { //从请求中读取文件 //f, err := c.formfile("f1") //和从请求中获取携带的参数一样 //if err != nil { // c.json(http.statusbadrequest, gin.h{ // "error": err.error(), // }) //}else { // //将读取到的文件保存到本地(服务端) // //dst := fmt.sprintf("./%s", f.filename) // dst := path.join("./", f.filename) // _ = c.saveuploadedfile(f,dst) // c.json(http.statusok, gin.h{ // "status":"ok", // }) //} form, _ := c.multipartform() files := form.file["f1"] for _, file := range files { log.print(file.filename) dst := path.join("./", file.filename) //上传文件到指定的目录 c.saveuploadedfile(file, dst) } c.json(http.statusok, gin.h{ "message" : fmt.sprintf("%d files uploaded!", len(files)), }) }) r.run(":9090") }