Skip to content

Commit

Permalink
feat(api): UploadFile support uploads binary file
Browse files Browse the repository at this point in the history
  • Loading branch information
Abdul R. Wahid authored and crispgm committed Mar 25, 2024
1 parent 7ae6746 commit 31928ff
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 9 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,9 @@
# CHANGELOG

## v1.14.1

- feat(api): UploadFile support uploads binary file

## v1.14.0

- refactor(im): build reply and update message with standalone methods
Expand Down
26 changes: 17 additions & 9 deletions api_upload.go
Expand Up @@ -29,10 +29,11 @@ type UploadImageResponse struct {

// UploadFileRequest .
type UploadFileRequest struct {
FileType string `json:"-"`
FileName string `json:"-"`
Duration int `json:"-"`
Path string `json:"-"`
FileType string `json:"-"`
FileName string `json:"-"`
Duration int `json:"-"`
Path string `json:"-"`
Reader io.Reader `json:"-"`
}

// UploadFileResponse .
Expand Down Expand Up @@ -105,11 +106,18 @@ func (bot Bot) UploadImageObject(img image.Image) (*UploadImageResponse, error)

// UploadFile uploads file to Lark server
func (bot Bot) UploadFile(req UploadFileRequest) (*UploadFileResponse, error) {
file, err := os.Open(req.Path)
if err != nil {
return nil, err
var content io.Reader
if req.Reader == nil {
file, err := os.Open(req.Path)
if err != nil {
return nil, err
}
defer file.Close()
content = file
} else {
content = req.Reader
req.Path = req.FileName
}
defer file.Close()

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
Expand All @@ -122,7 +130,7 @@ func (bot Bot) UploadFile(req UploadFileRequest) (*UploadFileResponse, error) {
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
_, err = io.Copy(part, content)
if err != nil {
return nil, err
}
Expand Down
17 changes: 17 additions & 0 deletions api_upload_test.go
Expand Up @@ -3,6 +3,7 @@ package lark
import (
"image/jpeg"
"os"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -41,3 +42,19 @@ func TestUploadFile(t *testing.T) {
assert.NotEmpty(t, resp.Data.FileKey)
}
}

func TestUploadFile_Binary(t *testing.T) {
resp, err := bot.UploadFile(UploadFileRequest{
FileType: "stream",
FileName: "test-data.csv",
Reader: strings.NewReader(`Name,Age,Location
Foo,25,Sleman
Bar,23,Sidoarjo
Baz,27,Bantul`),
})
if assert.NoError(t, err) {
assert.Zero(t, resp.Code)
t.Log(resp.Data.FileKey)
assert.NotEmpty(t, resp.Data.FileKey)
}
}

0 comments on commit 31928ff

Please sign in to comment.