【问题标题】:Posting image file from console application to API as an IFormFile parameter将图像文件从控制台应用程序作为 IFormFile 参数发布到 API
【发布时间】:2021-02-18 13:40:03
【问题描述】:

我需要将图像从 Asp.Net Core 控制台应用程序上传到 API。

发布到的 API 看起来像这样,并且在使用 Postman 测试时可以正常工作:

[HttpPost("UploadImage")]
public async Task<string> UploadImage(IFormFile files)
{
      // stuff happens here
}

将文件从控制台应用程序发布到此代码会是什么样子? 谢谢

【问题讨论】:

标签: c# asp.net api asp.net-core


【解决方案1】:

我需要从 Asp.Net Core 控制台应用程序将图像上传到 API。

要实现从Console应用发送图片到API后端的HTTP请求,可以参考以下代码sn-p。

var _httpClient = new HttpClient();

var formContent = new MultipartFormDataContent();

var FilePath = @"D:\xxx\pic1.PNG";

formContent.Add(new StreamContent(File.OpenRead(FilePath)), "files", Path.GetFileName(FilePath));

_httpClient.BaseAddress = new Uri("https://localhost:44312/");

var response = await _httpClient.PostAsync("/UploadImage", formContent);

if (response.IsSuccessStatusCode)
{
    //....
    //code logic here
    //...
}

【讨论】:

    【解决方案2】:

    我有一个包含表单文件操作的库。 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

    我还没有创建文档,但是代码内文档随处可见。我的目标是在未来把它变成一个框架。如果你能做出贡献,我会很高兴。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多