feat: 添加下载文件到浏览器功能
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -223,3 +224,45 @@ func DownloadToFile(ctx context.Context, fileURL string, localPath string) (err
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DownloadToBrowser 下载文件到浏览器(返回文件流,由 HTTP Response 直接写出)
|
||||
// 参数 fileURL: MinIO 中的对象路径(即 objectName)
|
||||
// 返回: 文件字节流、文件名、ContentType、错误
|
||||
func DownloadToBrowser(ctx context.Context, fileURL string) (fileBytes []byte, fileName string, contentType string, err error) {
|
||||
bucketName, err := utils.GetBucketName(ctx)
|
||||
if err != nil {
|
||||
glog.Errorf(ctx, "获取桶名称失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取对象流
|
||||
object, err := minioClient.GetObject(ctx, bucketName, fileURL, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
glog.Errorf(ctx, "获取文件流失败: %v", err)
|
||||
return
|
||||
}
|
||||
defer object.Close()
|
||||
|
||||
// 获取对象元信息(用于读取 ContentType 和 Size)
|
||||
info, err := object.Stat()
|
||||
if err != nil {
|
||||
glog.Errorf(ctx, "获取文件信息失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 读取全部内容
|
||||
fileBytes, err = io.ReadAll(object)
|
||||
if err != nil {
|
||||
glog.Errorf(ctx, "读取文件流失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 提取文件名
|
||||
fileName = filepath.Base(fileURL)
|
||||
contentType = info.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user