This repository has been archived by the owner on Jul 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
FileUploader.cs
160 lines (140 loc) · 6.57 KB
/
FileUploader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using Amazon.S3;
using Amazon.S3.Model;
using Blazor.FileReader;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Buffers;
using Microsoft.Extensions.Logging;
namespace CloudMosaic.BlazorFrontend
{
public interface IFileUploader
{
public Task<string> UploadFileAsync(IFileReference fileReference, Action<UploadEvent> callback);
}
public class FileUploader : IFileUploader
{
AppOptions _appOptions;
IAmazonS3 _s3Client;
ILogger<FileUploader> _logger;
const int PART_SIZE = 6 * 1024 * 1024;
const int READ_BUFFER_SIZE = 20000;
public FileUploader(IOptions<AppOptions> appOptions, ILogger<FileUploader> logger, IAmazonS3 s3Client)
{
_appOptions = appOptions.Value;
_logger = logger;
_s3Client = s3Client;
}
public async Task<string> UploadFileAsync(IFileReference fileReference, Action<UploadEvent> callback)
{
var objectKey = $"{_appOptions.UploadBucketPrefix}/{Guid.NewGuid()}";
this._logger.LogInformation($"Start uploading to {objectKey}");
var initateResponse = await _s3Client.InitiateMultipartUploadAsync(new InitiateMultipartUploadRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey
});
this._logger.LogInformation($"Initiated multi part upload with id {initateResponse.UploadId}");
try
{
using var inputStream = await fileReference.OpenReadAsync();
var partETags = new List<PartETag>();
var readBuffer = ArrayPool<byte>.Shared.Rent(READ_BUFFER_SIZE);
var partBuffer = ArrayPool<byte>.Shared.Rent(PART_SIZE + (READ_BUFFER_SIZE * 3));
var callbackEvent = new UploadEvent();
MemoryStream nextUploadBuffer = new MemoryStream(partBuffer);
try
{
int partNumber = 1;
int readCount;
while((readCount = (await inputStream.ReadAsync(readBuffer, 0, readBuffer.Length))) != 0)
{
callbackEvent.UploadBytes += readCount;
callback?.Invoke(callbackEvent);
await nextUploadBuffer.WriteAsync(readBuffer, 0, readCount);
if(PART_SIZE < nextUploadBuffer.Position)
{
var isLastPart = readCount == READ_BUFFER_SIZE;
var partSize = nextUploadBuffer.Position;
nextUploadBuffer.Position = 0;
var partResponse = await _s3Client.UploadPartAsync(new UploadPartRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey,
UploadId = initateResponse.UploadId,
InputStream = nextUploadBuffer,
PartSize = partSize,
PartNumber = partNumber,
IsLastPart = isLastPart
});
this._logger.LogInformation($"Uploaded part {partNumber}. (Last part = {isLastPart}, Part size = {partSize}, Upload Id: {initateResponse.UploadId}");
partETags.Add(new PartETag { PartNumber = partResponse.PartNumber, ETag = partResponse.ETag });
partNumber++;
nextUploadBuffer = new MemoryStream(partBuffer);
callbackEvent.UploadParts++;
callback?.Invoke(callbackEvent);
}
}
if(nextUploadBuffer.Position != 0)
{
var partSize = nextUploadBuffer.Position;
nextUploadBuffer.Position = 0;
var partResponse = await _s3Client.UploadPartAsync(new UploadPartRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey,
UploadId = initateResponse.UploadId,
InputStream = nextUploadBuffer,
PartSize = partSize,
PartNumber = partNumber,
IsLastPart = true
});
this._logger.LogInformation($"Uploaded final part. (Part size = {partSize}, Upload Id: {initateResponse.UploadId})");
partETags.Add(new PartETag { PartNumber = partResponse.PartNumber, ETag = partResponse.ETag });
callbackEvent.UploadParts++;
callback?.Invoke(callbackEvent);
}
}
finally
{
ArrayPool<byte>.Shared.Return(partBuffer);
ArrayPool<byte>.Shared.Return(readBuffer);
}
await _s3Client.CompleteMultipartUploadAsync(new CompleteMultipartUploadRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey,
UploadId = initateResponse.UploadId,
PartETags = partETags
});
this._logger.LogInformation($"Completed multi part upload. (Part count: {partETags.Count}, Upload Id: {initateResponse.UploadId})");
}
catch(Exception e)
{
await _s3Client.AbortMultipartUploadAsync(new AbortMultipartUploadRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey,
UploadId = initateResponse.UploadId
});
this._logger.LogError($"Error uploading to S3 with error: {e.Message}");
throw;
}
return _s3Client.GetPreSignedURL(new GetPreSignedUrlRequest
{
BucketName = _appOptions.MosaicStorageBucket,
Key = objectKey,
Verb = HttpVerb.GET,
Expires = DateTime.UtcNow.AddDays(1)
});
}
}
public class UploadEvent
{
public long UploadBytes { get; set; }
public int UploadParts { get; set; }
}
}