-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.go
More file actions
109 lines (89 loc) · 1.88 KB
/
file.go
File metadata and controls
109 lines (89 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package wxsender
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type Type string
const (
File Type = "file"
Voice Type = "voice"
)
const baseUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?"
type FileHelper struct {
Type Type // 文件类型
FilePath string // 文件路径
Key string // 文件名
UrlPrefix string // 文件上传地址前缀, 默认为: https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?
Response FileResponse
Err error
}
type FileResponse struct {
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
Type string `json:"type"`
MediaId string `json:"media_id"`
CreateAt int64 `json:"create_at"`
}
func (f *FileHelper) Upload() *FileHelper {
if f.UrlPrefix == "" {
f.UrlPrefix = baseUrl
}
url := f.UrlPrefix + "key=" + f.Key + "&type=" + string(f.Type)
file, err := os.Open(f.FilePath)
if err != nil {
f.Err = err
return f
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("media", filepath.Base(f.FilePath))
if err != nil {
f.Err = err
return f
}
_, err = io.Copy(part, file)
if err != nil {
f.Err = err
return f
}
err = writer.Close()
if err != nil {
f.Err = err
return f
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
f.Err = err
return f
}
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
f.Err = err
return f
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
f.Err = err
return f
}
var fileResp FileResponse
err = json.Unmarshal(respBody, &fileResp)
if err != nil {
f.Err = err
return f
}
f.Response = fileResp
return f
}
func (f *FileHelper) IsOk() bool {
return f.Response.Errcode == 0
}