59 lines
1.9 KiB
C#

using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Marco.Pms.Model.Utilities;
using Microsoft.Extensions.Options;
namespace Marco.Pms.Services.Service
{
public class S3UploadService
{
private readonly IAmazonS3 _s3Client;
private readonly string _bucketName = "your-bucket-name";
public S3UploadService(IOptions<AWSSettings> awsOptions)
{
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 = $"{Guid.NewGuid()}_{fileName}";
var uploadRequest = new TransferUtilityUploadRequest
{
InputStream = fileStream,
Key = objectKey,
BucketName = _bucketName,
ContentType = contentType,
AutoCloseStream = true
};
var transferUtility = new TransferUtility(_s3Client);
await transferUtility.UploadAsync(uploadRequest);
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);
return url;
}
}
}