feat(api): 支持OSS文件上传时指定Content-Type

- 在UploadFileToOSS函数中新增contentType参数
- 设置请求头Content-Length和Content-Type
- 为图片上传指定image/jpeg类型
- 增加上传失败时的日志记录
- 引入zap日志库支持结构化日志输出
This commit is contained in:
2025-11-24 18:09:38 +08:00
parent f10b68e487
commit a678829f59
2 changed files with 11 additions and 5 deletions

View File

@@ -2,6 +2,7 @@ package api
import (
"ZhenTuLocalPassiveAdapter/config"
"ZhenTuLocalPassiveAdapter/logger"
"bytes"
"context"
"encoding/json"
@@ -9,6 +10,8 @@ import (
"io"
"net/http"
"time"
"go.uber.org/zap"
)
// VIID Request/Response Structures
@@ -189,11 +192,13 @@ func SubmitFailure(ctx context.Context, taskID int64, errorCode, errorMessage st
return nil
}
func UploadFileToOSS(ctx context.Context, uploadUrl string, data []byte) error {
func UploadFileToOSS(ctx context.Context, uploadUrl string, data []byte, contentType string) error {
req, err := http.NewRequestWithContext(ctx, "PUT", uploadUrl, bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
req.Header.Set("Content-Type", contentType)
resp, err := GetUploadClient().Do(req)
if err != nil {
@@ -202,6 +207,8 @@ func UploadFileToOSS(ctx context.Context, uploadUrl string, data []byte) error {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
logger.Error("oss upload failed", zap.String("body", string(body)))
return fmt.Errorf("oss upload failed: %d", resp.StatusCode)
}
return nil

View File

@@ -4,7 +4,6 @@ import (
"ZhenTuLocalPassiveAdapter/logger"
"context"
"fmt"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
@@ -26,7 +25,7 @@ func UploadFaceData(ctx context.Context, scenicId int64, deviceNo string, faceIm
// Upload Face Image
g.Go(func() error {
if len(faceImg) > 0 {
if err := UploadFileToOSS(subCtx, uploadConfig.FaceUploadURL, faceImg); err != nil {
if err := UploadFileToOSS(subCtx, uploadConfig.FaceUploadURL, faceImg, "image/jpeg"); err != nil {
return fmt.Errorf("upload face image failed: %w", err)
}
}
@@ -36,7 +35,7 @@ func UploadFaceData(ctx context.Context, scenicId int64, deviceNo string, faceIm
// Upload Thumbnail Image
g.Go(func() error {
if len(thumbImg) > 0 {
if err := UploadFileToOSS(subCtx, uploadConfig.ThumbnailUploadURL, thumbImg); err != nil {
if err := UploadFileToOSS(subCtx, uploadConfig.ThumbnailUploadURL, thumbImg, "image/jpeg"); err != nil {
return fmt.Errorf("upload thumbnail image failed: %w", err)
}
}
@@ -46,7 +45,7 @@ func UploadFaceData(ctx context.Context, scenicId int64, deviceNo string, faceIm
// Upload Source Image
g.Go(func() error {
if len(srcImg) > 0 {
if err := UploadFileToOSS(subCtx, uploadConfig.SourceUploadURL, srcImg); err != nil {
if err := UploadFileToOSS(subCtx, uploadConfig.SourceUploadURL, srcImg, "image/jpeg"); err != nil {
return fmt.Errorf("upload source image failed: %w", err)
}
}