Blame view

API/Upload.go 2.18 KB
74de40c6   aarongao   init
1
2
3
package Api

import (
cfcccc99   aarongao   ok
4
	"encoding/base64"
74de40c6   aarongao   init
5
6
7
	"fmt"
	"github.com/aarongao/tools"
	"github.com/gin-gonic/gin"
cfcccc99   aarongao   ok
8
	"io/ioutil"
74de40c6   aarongao   init
9
10
	"path"
	"strconv"
cfcccc99   aarongao   ok
11
	"strings"
74de40c6   aarongao   init
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
	"time"
)

// @Title 上传文件
// @Description 上传
// @Accept  json
// @Produce  json
// @Param   file     1    file     true        "文件"
// @Success 200 {object} tools.ResponseSeccess "{"errcode":0,"result":"图片地址"}"
// @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}"
// @Router /Upload? [post]
func Upload(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
	c.Header("Access-Control-Allow-Credentials", "true")

	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(200, tools.ResponseError{
			1,
			"a Bad request",
		})
		return
	}

	fileName := file.Filename
	fileExt := path.Ext(fileName)
	filePath := "Upload/" + strconv.Itoa(int(time.Now().UnixNano())) + fileExt

	if err := c.SaveUploadedFile(file, filePath); err != nil {
		fmt.Println(err)
		c.JSON(200, tools.ResponseError{
			1,
			"upload file err",
		})
		return
	}
	c.JSON(200, tools.ResponseSeccess{
		0,
		"/" + filePath,
	})
}
cfcccc99   aarongao   ok
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

// @Title 上传文件BASE64
// @Description 上传文件BASE64
// @Accept  json
// @Produce  json
// @Param   file     1    file     true        "文件"
// @Success 200 {object} tools.ResponseSeccess "{"errcode":0,"result":"图片地址"}"
// @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}"
// @Router /UploadBASE64? [post]
func UploadBASE64(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
	c.Header("Access-Control-Allow-Credentials", "true")

	base64Img := c.PostForm("base64Img")

	index := strings.Index(base64Img, ",")
	base64Img = base64Img[index+1:]
	dist, _ := base64.StdEncoding.DecodeString(base64Img)

	fileExt := ".jpg"
	filePath := "Upload/" + strconv.Itoa(int(time.Now().UnixNano())) + fileExt

	err := ioutil.WriteFile(filePath, []byte(dist), 0666) //buffer输出到jpg文件中(不做处理,直接写到文件)
	if err != nil {
		fmt.Println(err)
		c.JSON(200, tools.ResponseError{
			1,
			"upload file err",
		})
		return
	}
	c.JSON(200, tools.ResponseSeccess{
		0,
		"/" + filePath,
	})
}