67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package image_converter
|
|
|
|
import (
|
|
"ai_scheduler/internal/config"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
)
|
|
|
|
// Client 图片转换器
|
|
type Client struct {
|
|
cfg config.ToolConfig
|
|
}
|
|
|
|
func New(cfg config.ToolConfig) *Client {
|
|
return &Client{
|
|
cfg: cfg,
|
|
}
|
|
}
|
|
|
|
// Call 将 Excel 文件转换为图片
|
|
func (c *Client) Call(filename string, fileBytes []byte, scale int) ([]byte, error) {
|
|
body := &bytes.Buffer{}
|
|
writer := multipart.NewWriter(body)
|
|
|
|
part, err := writer.CreateFormFile("file", filename)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err = io.Copy(part, bytes.NewReader(fileBytes)); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 添加 scale 参数
|
|
if scale <= 0 {
|
|
scale = 2
|
|
}
|
|
if err = writer.WriteField("scale", fmt.Sprintf("%d", scale)); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err = writer.Close(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", c.cfg.BaseURL, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", writer.FormDataContentType())
|
|
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("excel2pic service returned status: %s", resp.Status)
|
|
}
|
|
|
|
return io.ReadAll(resp.Body)
|
|
}
|