单文件上传
package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
)
// 解决跨域问题
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
//fmt.Println(method)
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-requested-with")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Expose-Headers", "Content-Type,Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
// 放行所有OPTIONS方法,因为有的模板是要请求两次的
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}
func main() {
r := gin.Default()
r.Use(Cors())
r.POST("/upload", func(c *gin.Context) {
file, _ := c.FormFile("file")
dir_path := "./runtime/"
file_path := fmt.Sprintf("%s %d %s", dir_path, (time.Now()).Unix(), file.Filename)
os.Mkdir("./runtime", os.ModePerm) // 创建文件夹
c.SaveUploadedFile(file, file_path) // 保存上传文件到指定路径
c.JSON(200, gin.H{
"msg": "upload succeed",
})
})
r.Run(":8080") // Run("里面不指定端口号默认为8080")
}
使用 CURL调试
#!/usr/bin/env bash
__curl_update() {
echo "$(date)" >/tmp/go-testfile.txt
curl http://localhost:8080/upload \
-X POST \
-H "Content-Type: multipart/form-data" \
-F "file=@/tmp/go-testfile.txt"
}
__curl_update
结果
