add upload file example.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
		
							
								
								
									
										34
									
								
								examples/upload-file/single/main.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										34
									
								
								examples/upload-file/single/main.go
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,34 @@
 | 
			
		||||
package main
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"io"
 | 
			
		||||
	"net/http"
 | 
			
		||||
	"os"
 | 
			
		||||
 | 
			
		||||
	"github.com/gin-gonic/gin"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func main() {
 | 
			
		||||
	router := gin.Default()
 | 
			
		||||
	router.Static("/", "./public")
 | 
			
		||||
	router.POST("/upload", func(c *gin.Context) {
 | 
			
		||||
		name := c.PostForm("name")
 | 
			
		||||
		email := c.PostForm("email")
 | 
			
		||||
 | 
			
		||||
		// Source
 | 
			
		||||
		file, _ := c.FormFile("file")
 | 
			
		||||
		src, _ := file.Open()
 | 
			
		||||
		defer src.Close()
 | 
			
		||||
 | 
			
		||||
		// Destination
 | 
			
		||||
		dst, _ := os.Create(file.Filename)
 | 
			
		||||
		defer dst.Close()
 | 
			
		||||
 | 
			
		||||
		// Copy
 | 
			
		||||
		io.Copy(dst, src)
 | 
			
		||||
 | 
			
		||||
		c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email))
 | 
			
		||||
	})
 | 
			
		||||
	router.Run(":8080")
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										16
									
								
								examples/upload-file/single/public/index.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								examples/upload-file/single/public/index.html
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,16 @@
 | 
			
		||||
<!doctype html>
 | 
			
		||||
<html lang="en">
 | 
			
		||||
<head>
 | 
			
		||||
    <meta charset="utf-8">
 | 
			
		||||
    <title>Single file upload</title>
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
<h1>Upload single file with fields</h1>
 | 
			
		||||
 | 
			
		||||
<form action="/upload" method="post" enctype="multipart/form-data">
 | 
			
		||||
    Name: <input type="text" name="name"><br>
 | 
			
		||||
    Email: <input type="email" name="email"><br>
 | 
			
		||||
    Files: <input type="file" name="file"><br><br>
 | 
			
		||||
    <input type="submit" value="Submit">
 | 
			
		||||
</form>
 | 
			
		||||
</body>
 | 
			
		||||
		Reference in New Issue
	
	Block a user