Skip to content

Commit

Permalink
add NewImageFromFile
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnNON committed Aug 20, 2023
1 parent 2410252 commit 3dd584b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 18 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func main() {
log.Fatal(err)
}

img, err := imgBB.NewImage(hashSum(b), 60, b)
img, err := imgBB.NewImageFromFile(hashSum(b), 60, b)
if err != nil {
log.Fatal(err)
}
Expand Down
55 changes: 38 additions & 17 deletions imgbb.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,31 @@ var (

// Image is a struct with image data to upload.
type Image struct {
name string
size int
ttl uint64
file []byte
name string
size int
ttl uint64
source string
file []byte
}

// NewImage creates a new Image.
func NewImage(name string, ttl uint64, file []byte) (*Image, error) {
func NewImage(name string, ttl uint64, source string) (*Image, error) {
size := len(source)

if size <= 0 {
return nil, ErrFileEmpty
}

return &Image{
name: name,
size: size,
ttl: ttl,
source: source,
}, nil
}

// NewImageFromFile creates a new Image from file.
func NewImageFromFile(name string, ttl uint64, file []byte) (*Image, error) {
size := len(file)

if size <= 0 {
Expand Down Expand Up @@ -156,29 +173,33 @@ func (i *Client) prepareRequest(ctx context.Context, img *Image) (*http.Request,
return
}

err = mpWriter.WriteField("type", "file")
if err != nil {
return
}

err = mpWriter.WriteField("action", "upload")
if err != nil {
return
}

if img.ttl > 0 {
err = mpWriter.WriteField("expiration", strconv.FormatUint(img.ttl, 10))
if err != nil {
return
}
}

part, err := mpWriter.CreateFormFile("image", img.name)
if img.file != nil {
part, err := mpWriter.CreateFormFile("image", img.name)
if err != nil {
return
}

if _, err = io.Copy(part, bytes.NewReader(img.file)); err != nil {
return
}

return
}

err = mpWriter.WriteField("name", img.name)
if err != nil {
return
}

if _, err = io.Copy(part, bytes.NewReader(img.file)); err != nil {
err = mpWriter.WriteField("image", img.source)
if err != nil {
return
}
}()
Expand Down

0 comments on commit 3dd584b

Please sign in to comment.