|
1 | 1 | // Copyright (c) Bynder. All rights reserved. |
2 | 2 | // Licensed under the MIT License. See LICENSE file in the project root for full license information. |
3 | 3 |
|
| 4 | +using System; |
4 | 5 | using System.Collections.Generic; |
5 | 6 | using System.IO; |
6 | 7 | using System.Net.Http; |
@@ -110,16 +111,20 @@ private async Task<SaveMediaResponse> UploadFileAsync(Stream fileStream, UploadQ |
110 | 111 | { |
111 | 112 | uint chunkNumber = 0; |
112 | 113 | var uploadRequest = await GetUploadRequest(filename); |
113 | | - using (fileStream) |
| 114 | + |
| 115 | + await using (fileStream) |
114 | 116 | { |
115 | | - int bytesRead = 0; |
116 | | - var buffer = new byte[CHUNK_SIZE]; |
117 | | - long numberOfChunks = (fileStream.Length + CHUNK_SIZE - 1) / CHUNK_SIZE; |
| 117 | + byte[] buffer = new byte[CHUNK_SIZE]; |
| 118 | + long numberOfChunks = (fileStream.Length + buffer.Length - 1) / buffer.Length; |
| 119 | + long totalBytesRead = 0; |
118 | 120 |
|
119 | | - while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) |
| 121 | + while (totalBytesRead < fileStream.Length) |
120 | 122 | { |
121 | | - ++chunkNumber; |
122 | | - await UploadPartAsync(Path.GetFileName(query.Filepath), buffer, bytesRead, chunkNumber, uploadRequest, (uint)numberOfChunks).ConfigureAwait(false); |
| 123 | + int bytesToRead = (int)Math.Min(buffer.Length, fileStream.Length - totalBytesRead); |
| 124 | + |
| 125 | + await UploadChunkAsync(uploadRequest, filename, fileStream, buffer, bytesToRead, numberOfChunks, ++chunkNumber); |
| 126 | + |
| 127 | + totalBytesRead += bytesToRead; |
123 | 128 | } |
124 | 129 | } |
125 | 130 |
|
@@ -147,6 +152,25 @@ private async Task<SaveMediaResponse> UploadFileAsync(Stream fileStream, UploadQ |
147 | 152 | } |
148 | 153 | } |
149 | 154 |
|
| 155 | + private async Task UploadChunkAsync(UploadRequest uploadRequest, string fileName, Stream fileStream, byte[] buffer, int bytesToRead, long numberOfChunks, uint chunkNumber) |
| 156 | + { |
| 157 | + int bytesReadForChunk = 0; |
| 158 | + |
| 159 | + while (bytesReadForChunk < bytesToRead) |
| 160 | + { |
| 161 | + int bytesRead = await fileStream.ReadAsync(buffer, bytesReadForChunk, bytesToRead - bytesReadForChunk); |
| 162 | + |
| 163 | + if (bytesRead == 0) |
| 164 | + { |
| 165 | + throw new EndOfStreamException(); |
| 166 | + } |
| 167 | + |
| 168 | + bytesReadForChunk += bytesRead; |
| 169 | + } |
| 170 | + |
| 171 | + await UploadPartAsync(fileName, buffer, bytesReadForChunk, chunkNumber, uploadRequest, (uint)numberOfChunks).ConfigureAwait(false); |
| 172 | + } |
| 173 | + |
150 | 174 | /// <summary> |
151 | 175 | /// Gets the closest s3 endpoint. This is needed to know to which bucket Url it uploads chunks |
152 | 176 | /// </summary> |
|
0 commit comments