71 lines
2.6 KiB
C#
71 lines
2.6 KiB
C#
using Amazon.S3;
|
|
using Amazon.S3.Model;
|
|
using Amazon.S3.Transfer;
|
|
using Marco.Pms.Model.Utilities;
|
|
using MarcoBMS.Services.Service;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Marco.Pms.Services.Service
|
|
{
|
|
|
|
public class S3UploadService
|
|
{
|
|
private readonly IAmazonS3 _s3Client;
|
|
private readonly string _bucketName = "your-bucket-name";
|
|
private readonly ILoggingService _logger;
|
|
|
|
public S3UploadService(IOptions<AWSSettings> awsOptions, ILoggingService logger)
|
|
{
|
|
_logger = logger;
|
|
var settings = awsOptions.Value;
|
|
|
|
var region = Amazon.RegionEndpoint.GetBySystemName(settings.Region);
|
|
_bucketName = settings.BucketName;
|
|
|
|
_s3Client = new AmazonS3Client(settings.AccessKey, settings.SecretKey, region);
|
|
}
|
|
//public async Task<string> UploadFileAsync(string fileName, string contentType)
|
|
public async Task<string> UploadFileAsync(Stream fileStream, string fileName, string contentType)
|
|
{
|
|
// Generate a unique object key (you can customize this)
|
|
var objectKey = $"{fileName}";
|
|
|
|
var uploadRequest = new TransferUtilityUploadRequest
|
|
{
|
|
InputStream = fileStream,
|
|
Key = objectKey,
|
|
BucketName = _bucketName,
|
|
ContentType = contentType,
|
|
AutoCloseStream = true
|
|
};
|
|
|
|
var transferUtility = new TransferUtility(_s3Client);
|
|
await transferUtility.UploadAsync(uploadRequest);
|
|
_logger.LogInfo("File uploaded to Amazon S3");
|
|
return objectKey;
|
|
}
|
|
public async Task<string> GeneratePreSignedUrlAsync(string objectKey)
|
|
{
|
|
int expiresInMinutes = 1;
|
|
var request = new GetPreSignedUrlRequest
|
|
{
|
|
BucketName = _bucketName,
|
|
Key = objectKey,
|
|
Expires = DateTime.UtcNow.AddMinutes(expiresInMinutes),
|
|
Verb = HttpVerb.GET // for download
|
|
};
|
|
|
|
string url = _s3Client.GetPreSignedURL(request);
|
|
_logger.LogInfo("Requested presigned url from Amazon S3");
|
|
return url;
|
|
}
|
|
public string GenerateFileName(string contentType, int tenantId, string? name)
|
|
{
|
|
string extenstion = contentType.Split("/")[1];
|
|
if (string.IsNullOrEmpty(name))
|
|
return $"{tenantId}_{DateTime.UtcNow:yyyyMMddHHmmssfff}.{extenstion}";
|
|
return $"{name}_{tenantId}_{DateTime.UtcNow:yyyyMMddHHmmssfff}.{extenstion}";
|
|
|
|
}
|
|
}
|
|
} |