我有一个包含表单文件操作的库。 ConvertToFormFile 方法在我的库中。但是由于 Memory Stream,您不能使用外部程序集。因此,您可以在自己的类中定义此方法,也可以将其定义为扩展方法。
public class ProductDTO {
private string _imageBase64String;
public int Id { get; set; }
public string ImageBase64String
{
get => _imageBase64String;
set
{
if (!string.IsNullOrEmpty(value))
{
Image = ConvertToFormFile(value);
}
_imageBase64String = value;
}
}
public IFormFile Image { get; set; }
/// <summary>
/// Converts data URI formatted base64 string to IFormFile.
/// </summary>
/// <param name="milvaBase64"></param>
/// <returns></returns>
private IFormFile ConvertToFormFile(string milvaBase64)
{
var splittedBase64String = milvaBase64.Split(";base64,");
var base64String = splittedBase64String?[1];
var contentType = splittedBase64String[0].Split(':')[1];
var splittedContentType = contentType.Split('/');
var fileType = splittedContentType?[0];
var fileExtension = splittedContentType?[1];
var array = Convert.FromBase64String(base64String);
var memoryStream = new MemoryStream(array)
{
Position = 0
};
return new FormFile(memoryStream, 0, memoryStream.Length, fileType, $"File.{fileExtension}")
{
Headers = new HeaderDictionary(),
ContentType = contentType
};
}
}
uri 格式的 base64 字符串示例数据:data:image/jpeg;base64,/9j/2wCEAAgGBgcGBQgHBwcJCQgKDBQNDAsLDB...
然后您可以使用我的库来保存图像或做其他事情。如下所示;
public class ProductService{
...
private readonly IStringLocalizer<ProductService> _localizer;
...
public async Task SaveProductImage(ProductDTO productDTO)
{
var imagePath = await productDTO.Image.SaveImageToServerAsync<ProductDTO, int>(productDTO, _localizer).ConfigureAwait(false);
}
}
public static class HelperExtension{
/// <summary>
/// Save uploaded IFormFile file to server. Target Path will be : ".../wwwroot/Media Library/Image Library/<paramref name="entity"></paramref>.Id"
/// </summary>
/// <returns></returns>
public static async Task<string> SaveImageToServerAsync<TEntity, TKey>(this IFormFile file, TEntity entity, IStringLocalizer stringLocalizer) where TEntity : AuditableEntity<OpsiyonUser, Guid, TKey>
where TKey : struct, IEquatable<TKey>
{
string basePath = GlobalConstants.ImageLibraryPath;
FormFileOperations.FilesFolderNameCreator imagesFolderNameCreator = CreateImageFolderNameFromDTO;
string propertyName = "Id";
int maxFileLength = 14000000;
var allowedFileExtensions = GlobalConstants.AllowedFileExtensions.Find(i => i.FileType == FileType.Image.ToString()).AllowedExtensions;
var validationResult = file.ValidateFile(FileType.Image, maxFileLength, allowedFileExtensions);
switch (validationResult)
{
case FileValidationResult.Valid:
break;
case FileValidationResult.FileSizeTooBig:
// Get length of file in bytes
long fileSizeInBytes = file.Length;
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
double fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
double fileSizeInMB = fileSizeInKB / 1024;
throw new MilvaValidationException(stringLocalizer["FileIsTooBigMessage", fileSizeInMB.ToString("0.#")]);
case FileValidationResult.InvalidFileExtension:
var stringBuilder = new StringBuilder();
throw new MilvaValidationException(stringLocalizer["UnsupportedFileTypeMessage", stringBuilder.AppendJoin(", ", allowedFileExtensions)]);
case FileValidationResult.NullFile:
return "";
}
var path = await file.SaveFileToPathAsync(entity, basePath, imagesFolderNameCreator, propertyName).ConfigureAwait(false);
await file.OpenReadStream().DisposeAsync().ConfigureAwait(false);
return path;
}
private static string CreateImageFolderNameFromDTO(Type type)
{
return type.Name.Split("DTO")[0] + "Images";
}
}
或者您可以在 FormFileOperations.cs 中使用此方法,如下所示;
public async Task<IFormFile> GetFile()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.jpg");
return await FormFileOperations.GetFileFromPathAsync(path, FileType.Image).ConfigureAwait(false);
}
并使用 HttpClient 发送请求。
关于我的图书馆的详细信息请看一下;
Github link
Nuget link
我还没有创建文档,但是代码内文档随处可见。我的目标是在未来把它变成一个框架。如果你能做出贡献,我会很高兴。
希望对你有帮助。