Skip to content

Commit 617b655

Browse files
Add ReadAllAsync
1 parent 075a154 commit 617b655

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

BlazorInputFile/BlazorInputFile.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
55
<RazorLangVersion>3.0</RazorLangVersion>
66
<LangVersion>preview</LangVersion>
7-
<PackageVersion>0.1.0-preview</PackageVersion>
7+
<PackageVersion>0.1.0-preview-00002</PackageVersion>
88
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
99
</PropertyGroup>
1010

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System;
2+
using System.IO;
3+
using System.Threading.Tasks;
4+
5+
namespace BlazorInputFile
6+
{
7+
public static class FileListEntryExtensions
8+
{
9+
/// <summary>
10+
/// Reads the entire uploaded file into a <see cref="MemoryStream"/>. This will allocate
11+
/// however much memory is needed to hold the entire file, or will throw if the client
12+
/// tries to supply more than <paramref name="maxSizeBytes"/> bytes. Be careful not to
13+
/// let clients allocate too much memory on the server.
14+
/// </summary>
15+
/// <param name="fileListEntry">The <see cref="IFileListEntry"/>.</param>
16+
/// <param name="maxSizeBytes">The maximum amount of data to accept.</param>
17+
public static async Task<MemoryStream> ReadAllAsync(this IFileListEntry fileListEntry, int maxSizeBytes = 1024*1024)
18+
{
19+
if (fileListEntry is null)
20+
{
21+
throw new ArgumentNullException(nameof(fileListEntry));
22+
}
23+
24+
// We can trust .Length to be correct (and can't change later) because the implementation
25+
// won't supply more bytes than this, even if the JS-side code would send more data.
26+
var sourceData = fileListEntry.Data;
27+
if (sourceData.Length > maxSizeBytes)
28+
{
29+
throw new ArgumentOutOfRangeException(nameof(fileListEntry), $"The maximum allowed size is {maxSizeBytes}, but the supplied file is of length {fileListEntry.Size}.");
30+
}
31+
32+
var result = new MemoryStream();
33+
await sourceData.CopyToAsync(result);
34+
result.Seek(0, SeekOrigin.Begin);
35+
return result;
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)