71 lines
2.1 KiB
C#
71 lines
2.1 KiB
C#
|
|
using LMS.DAO.OptionDAO;
|
|||
|
|
using LMS.Tools.ImageTool;
|
|||
|
|
using static LMS.Repository.DTO.FileUploadDto;
|
|||
|
|
|
|||
|
|
namespace LMS.Tools.FileTool
|
|||
|
|
{
|
|||
|
|
public static class FileService
|
|||
|
|
{
|
|||
|
|
public static byte[]? ConvertBase64ToBytes(string base64String)
|
|||
|
|
{
|
|||
|
|
if (string.IsNullOrEmpty(base64String))
|
|||
|
|
{
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
// 检查是否以 "data:" 开头并包含 base64 编码,如果是则提取实际的 base64 部分
|
|||
|
|
if (base64String.StartsWith("data:"))
|
|||
|
|
{
|
|||
|
|
// 提取 base64 编码部分
|
|||
|
|
var commaIndex = base64String.IndexOf(',');
|
|||
|
|
if (commaIndex >= 0)
|
|||
|
|
{
|
|||
|
|
base64String = base64String.Substring(commaIndex + 1);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
// 尝试将 base64 字符串转换为字节数组
|
|||
|
|
return Convert.FromBase64String(base64String);
|
|||
|
|
}
|
|||
|
|
catch (FormatException)
|
|||
|
|
{
|
|||
|
|
// 如果格式不正确,返回 null
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static bool IsValidImageFile(byte[] fileBytes)
|
|||
|
|
{
|
|||
|
|
if (fileBytes == null || fileBytes.Length == 0)
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return ImageTypeDetector.IsValidImage(fileBytes);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static async Task<UploadResult> CheckFileSize(byte[] fileBytes, double MaxFileSize)
|
|||
|
|
{
|
|||
|
|
if (fileBytes == null || fileBytes.Length == 0)
|
|||
|
|
{
|
|||
|
|
return new UploadResult
|
|||
|
|
{
|
|||
|
|
Success = false,
|
|||
|
|
Message = "文件不能为空"
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (fileBytes.Length > MaxFileSize * 1024 * 1024)
|
|||
|
|
{
|
|||
|
|
return new UploadResult
|
|||
|
|
{
|
|||
|
|
Success = false,
|
|||
|
|
Message = $"文件大小({fileBytes.Length} bytes)超过限制({MaxFileSize * 1024 * 1024} bytes)"
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return new UploadResult { Success = true };
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|