Refactored the S3 services to properly upload the file
continuous-integration/drone/pr Build is passing

This commit is contained in:
Khwezi Mngoma
2026-05-20 08:01:44 +02:00
parent 89a343a85f
commit d6fdf1b9c8
12 changed files with 148 additions and 147 deletions
@@ -2,7 +2,41 @@
public abstract class S3ServiceBase(IAmazonS3 amazonS3)
{
protected readonly IAmazonS3 client = amazonS3;
protected readonly IAmazonS3 Client = amazonS3;
public abstract Task<Result<string>> UploadFileAsync(string fileName, Stream fileStream, string contentType, CancellationToken cancellationToken = default);
protected abstract string BucketName { get; }
protected abstract string CdnBaseUrl { get; }
public virtual async Task<Result<string>> UploadFileAsync(string fileName, Stream fileStream, string contentType, CancellationToken cancellationToken = default)
{
try
{
if (string.IsNullOrWhiteSpace(BucketName))
return Result.Fail<string>("Bucket name is not configured.");
if (string.IsNullOrWhiteSpace(CdnBaseUrl))
return Result.Fail<string>("CDN base URL is not configured.");
var fileKey = $"{Guid.NewGuid():N}{Path.GetExtension(fileName)}";
var putRequest = new PutObjectRequest
{
BucketName = BucketName,
Key = fileKey,
InputStream = fileStream,
ContentType = contentType,
UseChunkEncoding = false
};
var response = await Client.PutObjectAsync(putRequest, cancellationToken);
return response.HttpStatusCode != System.Net.HttpStatusCode.OK
? Result.Fail<string>($"Failed to upload {fileName} to S3.")
: Result.Ok($"{CdnBaseUrl}/{fileKey}");
}
catch (Exception ex)
{
return Result.Fail<string>(new Error($"Error uploading {fileName} to S3: {ex.Message}").CausedBy(ex));
}
}
}