Files
zmkgC/third/officeWeb365/office.go

113 lines
2.3 KiB
Go
Raw Permalink Normal View History

2025-07-07 20:11:59 +08:00
// @Author cory 2025/4/24 15:52:00
package officeWeb365
import (
"bytes"
"encoding/json"
"errors"
"github.com/tiger1103/gfast/v3/api/v1/common/coryCommon"
"golang.org/x/net/context"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
)
func SendFile199(ctx context.Context, relativePath string, typeStr string) (err error, urlPath string) {
//1、根据相对路径获取到文件信息
filePath := coryCommon.FileToFunc(relativePath, 2)
fieldName := "file" // 表单字段名
// 获取文件名
fileName := filepath.Base(filePath) // 自动获取 "222.xlsx"
// 打开文件
file, err := os.Open(filePath)
if err != nil {
panic(err)
}
defer file.Close()
// 创建 multipart body
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// 创建文件字段(自动带文件名)
part, err := writer.CreateFormFile(fieldName, fileName)
if err != nil {
panic(err)
}
// 将文件内容复制进去
_, err = io.Copy(part, file)
if err != nil {
panic(err)
}
// 关闭 multipart writer
err = writer.Close()
if err != nil {
panic(err)
}
url := ""
sip := "http://192.168.1.177:8188"
switch typeStr {
case "1":
url = sip + "/api/doc/view/uploadfile"
case "2":
url = sip + "/OnlineEditing/GetPreviewUrl"
case "3":
url = sip + "/api/ppt/view/uploadfile"
}
// 创建请求
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
panic(err)
}
// 设置 multipart Content-Type
req.Header.Set("Content-Type", writer.FormDataContentType())
// 发出请求
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err, ""
}
defer resp.Body.Close()
// 读取响应
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return errors.New("请求错误!"), ""
}
// 解析响应 JSON
var responseData ResponseData
err = json.Unmarshal(respBody, &responseData)
if err != nil {
return errors.New(string(respBody)), ""
}
// 输出结果
if responseData.Code == 200 {
return nil, strings.Replace(responseData.Data.ViewURL, sip, "", -1)
} else {
return errors.New("请求错误!"), ""
}
}
// ResponseData 定义响应数据的结构体
type ResponseData struct {
Code int `json:"code"`
Data struct {
RequestID string `json:"request_id"`
ViewURL string `json:"view_url"`
} `json:"data"`
Msg string `json:"msg"`
}