using Microsoft.Extensions.Logging;
using X1.Domain.ExternalCommunication.Models;
namespace X1.DynamicClientCore.Core
{
///
/// DynamicHttpClient 文件下载部分
/// 提供文件下载功能
///
public partial class DynamicHttpClient
{
#region 文件下载方法
///
/// 异步下载文件到指定路径
///
public async Task DownloadFileAsync(string serviceName, string endpoint, string localFilePath, RequestOptions? options = null)
{
try
{
var fileBytes = await DownloadFileAsBytesAsync(serviceName, endpoint, options);
if (fileBytes != null)
{
await File.WriteAllBytesAsync(localFilePath, fileBytes);
return true;
}
return false;
}
catch (Exception ex)
{
_logger.LogError(ex, "文件下载失败: {ServiceName}:{Endpoint} -> {LocalPath}", serviceName, endpoint, localFilePath);
return false;
}
}
///
/// 异步下载文件到流
///
public async Task DownloadFileToStreamAsync(string serviceName, string endpoint, Stream outputStream, RequestOptions? options = null)
{
try
{
var fileBytes = await DownloadFileAsBytesAsync(serviceName, endpoint, options);
if (fileBytes != null)
{
await outputStream.WriteAsync(fileBytes);
return true;
}
return false;
}
catch (Exception ex)
{
_logger.LogError(ex, "文件下载到流失败: {ServiceName}:{Endpoint}", serviceName, endpoint);
return false;
}
}
///
/// 异步下载文件为字节数组
///
public async Task DownloadFileAsBytesAsync(string serviceName, string endpoint, RequestOptions? options = null)
{
try
{
var response = await ExecuteRequestAsync(serviceName, endpoint, HttpMethod.Get, null, options);
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "文件下载为字节数组失败: {ServiceName}:{Endpoint}", serviceName, endpoint);
return null;
}
}
///
/// 同步下载文件到指定路径
///
public bool DownloadFile(string serviceName, string endpoint, string localFilePath, RequestOptions? options = null)
{
return DownloadFileAsync(serviceName, endpoint, localFilePath, options).GetAwaiter().GetResult();
}
///
/// 同步下载文件到流
///
public bool DownloadFileToStream(string serviceName, string endpoint, Stream outputStream, RequestOptions? options = null)
{
return DownloadFileToStreamAsync(serviceName, endpoint, outputStream, options).GetAwaiter().GetResult();
}
///
/// 同步下载文件为字节数组
///
public byte[]? DownloadFileAsBytes(string serviceName, string endpoint, RequestOptions? options = null)
{
return DownloadFileAsBytesAsync(serviceName, endpoint, options).GetAwaiter().GetResult();
}
#endregion
}
}