Skip to content

Commit

Permalink
fix image upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Ceelog committed Apr 1, 2021
1 parent ce33239 commit 2c6c439
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 23 deletions.
47 changes: 25 additions & 22 deletions apis/security/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ package security

import (
"bytes"
"io"
"io/ioutil"
"mime/multipart"
"os"
"path"
Expand All @@ -41,27 +41,30 @@ See: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-c
POST(@media) https://api.weixin.qq.com/wxa/img_sec_check?access_token=ACCESS_TOKEN
*/
func ImgSecCheck(ctx *miniprogram.Miniprogram, media string) (resp []byte, err error) {
r, w := io.Pipe()
m := multipart.NewWriter(w)
go func() {
defer w.Close()
defer m.Close()

part, err := m.CreateFormFile("media", path.Base(media))
if err != nil {
return
}
file, err := os.Open(media)
if err != nil {
return
}
defer file.Close()
if _, err = io.Copy(part, file); err != nil {
return
}

}()
return ctx.Client.HTTPPost(apiImgSecCheck, r, m.FormDataContentType())

file, err := os.Open(media)
if err != nil {
return nil, err
}
fileContents, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
file.Close()

body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("media", path.Base(media))
if err != nil {
return nil, err
}
part.Write(fileContents)

err = writer.Close()
if err != nil {
return nil, err
}
return ctx.Client.HTTPPost(apiImgSecCheck, body, writer.FormDataContentType())
}

/*
Expand Down
2 changes: 1 addition & 1 deletion apis/security/security_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestImgSecCheck(t *testing.T) {
wantResp []byte
wantErr bool
}{
{name: "case1", args: args{ctx: test.MockMiniprogram}, wantResp: mockResp["case1"], wantErr: false},
{name: "case1", args: args{ctx: test.MockMiniprogram, media: "security.go"}, wantResp: mockResp["case1"], wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 2c6c439

Please sign in to comment.