using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using SafetyHub.Api.Infrastructure.Config;
using SafetyHub.Api.Infrastructure.ExtensionMethods;
namespace SafetyHub.Api.Infrastructure.Helper
{
public class AwsS3 : IAwsS3
{
public async Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string keyName)
{
string extension = Path.GetExtension(file.FileName);
var filePath = keyName + "_" + DateTime.UtcNow.Ticks + extension;
using var newMemoryStream = new MemoryStream();
await file.CopyToAsync(newMemoryStream).ConfigureAwait(false);
var request = new PutObjectRequest
{
InputStream = newMemoryStream,
BucketName = Configs.AWSConfigurations.S3BucketName,
Key = filePath
};
var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });
var response = await _s3Client.PutObjectAsync(request).ConfigureAwait(false);
if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)
{
return (true, filePath);
}
return (false, Constant.HttpResponse.ERROR);
}
public async Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName)
{
try
{
var request = new GetObjectRequest
{
BucketName = Configs.AWSConfigurations.S3BucketName,
Key = keyName
};
var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });
var response = await _s3Client.GetObjectAsync(request).ConfigureAwait(false);
if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)
{
return (true, response.ResponseStream);
}
}
catch { }
return (false, null);
}
public async Task<(bool IsSuccess, string Result)> DeleteFile(string keyName)
{
var request = new DeleteObjectRequest
{
BucketName = Configs.AWSConfigurations.S3BucketName,
Key = keyName
};
var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });
var response = await _s3Client.DeleteObjectAsync(request).ConfigureAwait(false);
if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.NoContent) == true)
{
return (true, "File has been deleted successfully.");
}
return (false, "File no exists.");
}
}
public interface IAwsS3
{
Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string uploadPath);
Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName);
Task<(bool IsSuccess, string Result)> DeleteFile(string keyName);
}
}
0 Comments