Last active
March 31, 2022 11:56
-
-
Save fardeen9983/f289dc9e39d2ffced6a70d1cf13d8e85 to your computer and use it in GitHub Desktop.
File Upload Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Generates a presigned URL of the file if it is successfully uploaded to S3 | |
/// </summary> | |
/// <param name="file">File to be Uploaded</param> | |
/// <returns></returns> | |
public async Task<string> GetS3ObjectPresignedUrl(IFormFile file) | |
{ | |
try | |
{ | |
var key = Path.GetRandomFileName() + Guid.NewGuid().ToString() + Path.GetExtension(file.FileName).ToLowerInvariant(); | |
if (await UploadFileToS3(file, key)) | |
{ | |
var getUrlRequest = new GetPreSignedUrlRequest | |
{ | |
BucketName = BucketName, | |
Key = key, | |
Expires = DateTime.UtcNow.AddHours(ExpirationDurationInHours), | |
}; | |
return _client.GetPreSignedURL(getUrlRequest); | |
} | |
return null; | |
} | |
catch (AmazonS3Exception e) | |
{ | |
throw; | |
} | |
catch (Exception e) | |
{ | |
throw; | |
} | |
} | |
/// <summary> | |
/// Uploads the file to S3 Bucket if it exists | |
/// </summary> | |
/// <param name="file">Uploaded File</param> | |
/// <param name="key">Object Key for S3</param> | |
/// <returns></returns> | |
private async Task<bool> UploadFileToS3(IFormFile file, string key) | |
{ | |
try | |
{ | |
if (await AmazonS3Util.DoesS3BucketExistV2Async(_client, BucketName)) | |
{ | |
var transferUtilityConfig = new TransferUtilityConfig | |
{ | |
ConcurrentServiceRequests = 5, | |
MinSizeBeforePartUpload = 20 * MB, | |
}; | |
using (var transferUtility = new TransferUtility(_client, transferUtilityConfig)) | |
{ | |
var uploadRequest = new TransferUtilityUploadRequest | |
{ | |
Key = key, | |
BucketName = BucketName, | |
InputStream = file.OpenReadStream(), | |
PartSize = 20 * MB, | |
StorageClass = S3StorageClass.Standard, | |
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256, | |
}; | |
await transferUtility.UploadAsync(uploadRequest); | |
} | |
return true; | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
catch (Exception e) | |
{ | |
throw; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment