admin/src/Oms.Application/Shared/OmsManagedImageHelper.cs
zzh ef3a3abb9f
All checks were successful
Build and Deploy / deploy (push) Successful in 1m29s
fix: 封面图代理去掉 attachment,便于 CSS/img 内联展示
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 14:10:07 +08:00

162 lines
4.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.RegularExpressions;
using Fake.Application;
using Fake.ObjectStorage;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Storage;
namespace Oms.Application.Shared;
/// <summary>
/// 托管图片同源访问:存 object key,对外只签发 /xxx/file 相对路径(不签发 COS 直链)。
/// </summary>
public static class OmsManagedImageHelper
{
public const string SalesProductCoverFilePath = "/channel/sales-product/cover/file";
public const string SalesProductCoverKeyPrefix = "uploads/sales-product-cover/";
/// <summary>
/// 生成浏览器可直开的同源相对路径;物理文件可在 COS/Local,但不把 cos.* 签发给前端。
/// </summary>
public static string BuildSameOriginUrlByKey(string path, string? objectKey)
{
if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0")
{
return string.Empty;
}
string logicalKey;
try
{
logicalKey = FileStoragePath.NormalizeKey(objectKey);
}
catch
{
return string.Empty;
}
if (string.IsNullOrWhiteSpace(logicalKey))
{
return string.Empty;
}
var stamp = Path.GetFileNameWithoutExtension(logicalKey.Replace('\\', '/'));
if (string.IsNullOrWhiteSpace(stamp))
{
stamp = Math.Abs(logicalKey.GetHashCode(StringComparison.Ordinal)).ToString("x");
}
return $"{path}?key={Uri.EscapeDataString(logicalKey)}&v={Uri.EscapeDataString(stamp)}";
}
public static string BuildSalesProductCoverUrl(string? objectKey) =>
BuildSameOriginUrlByKey(SalesProductCoverFilePath, objectKey);
/// <summary>
/// 按 object key 输出图片字节(同源代理,避免浏览器直连 COS)。
/// </summary>
public static async Task<FileContentResult> StreamByKeyAsync(
IObjectStorage storage,
string? objectKey,
CancellationToken cancellationToken,
string? requiredKeyPrefix = null)
{
if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0")
{
throw new BusinessException("图片未配置");
}
string logicalKey;
try
{
logicalKey = FileStoragePath.NormalizeKey(objectKey);
}
catch
{
throw new BusinessException("图片路径无效");
}
if (!string.IsNullOrWhiteSpace(requiredKeyPrefix)
&& !logicalKey.StartsWith(requiredKeyPrefix, StringComparison.OrdinalIgnoreCase))
{
throw new BusinessException("图片路径无效");
}
foreach (var candidate in FileStoragePath.ExpandReadKeys(logicalKey))
{
try
{
if (!await storage.ExistsAsync(candidate, cancellationToken))
{
continue;
}
await using var stream = await storage.GetAsync(candidate, cancellationToken);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms, cancellationToken);
var bytes = ms.ToArray();
if (bytes.Length <= 0)
{
continue;
}
// 不设 FileDownloadName,避免 Content-Disposition: attachment 影响 CSS/img 内联展示
return new FileContentResult(bytes, GuessImageMime(candidate));
}
catch (UnauthorizedAccessException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (IOException)
{
}
}
throw new BusinessException("图片不存在或无法读取");
}
public static string GuessImageMime(string pathOrKey)
{
if (Regex.IsMatch(pathOrKey, @"\.png(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/png";
}
if (Regex.IsMatch(pathOrKey, @"\.jpe?g(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/jpeg";
}
if (Regex.IsMatch(pathOrKey, @"\.webp(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/webp";
}
if (Regex.IsMatch(pathOrKey, @"\.gif(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/gif";
}
if (Regex.IsMatch(pathOrKey, @"\.bmp(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/bmp";
}
if (Regex.IsMatch(pathOrKey, @"\.svg(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/svg+xml";
}
if (Regex.IsMatch(pathOrKey, @"\.ico(\?|#|$)", RegexOptions.IgnoreCase))
{
return "image/x-icon";
}
return "application/octet-stream";
}
}