From 617b65551062b38abffcbcde154285a51db64f91 Mon Sep 17 00:00:00 2001 From: Steve Sanderson Date: Tue, 24 Sep 2019 22:30:31 +0100 Subject: [PATCH] Add ReadAllAsync --- BlazorInputFile/BlazorInputFile.csproj | 2 +- BlazorInputFile/FileListEntryExtensions.cs | 38 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 BlazorInputFile/FileListEntryExtensions.cs diff --git a/BlazorInputFile/BlazorInputFile.csproj b/BlazorInputFile/BlazorInputFile.csproj index d9551e7..f449646 100644 --- a/BlazorInputFile/BlazorInputFile.csproj +++ b/BlazorInputFile/BlazorInputFile.csproj @@ -4,7 +4,7 @@ netstandard2.0;netstandard2.1 3.0 preview - 0.1.0-preview + 0.1.0-preview-00002 Apache-2.0 diff --git a/BlazorInputFile/FileListEntryExtensions.cs b/BlazorInputFile/FileListEntryExtensions.cs new file mode 100644 index 0000000..f2a4657 --- /dev/null +++ b/BlazorInputFile/FileListEntryExtensions.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Threading.Tasks; + +namespace BlazorInputFile +{ + public static class FileListEntryExtensions + { + /// + /// Reads the entire uploaded file into a . This will allocate + /// however much memory is needed to hold the entire file, or will throw if the client + /// tries to supply more than bytes. Be careful not to + /// let clients allocate too much memory on the server. + /// + /// The . + /// The maximum amount of data to accept. + public static async Task ReadAllAsync(this IFileListEntry fileListEntry, int maxSizeBytes = 1024*1024) + { + if (fileListEntry is null) + { + throw new ArgumentNullException(nameof(fileListEntry)); + } + + // We can trust .Length to be correct (and can't change later) because the implementation + // won't supply more bytes than this, even if the JS-side code would send more data. + var sourceData = fileListEntry.Data; + if (sourceData.Length > maxSizeBytes) + { + throw new ArgumentOutOfRangeException(nameof(fileListEntry), $"The maximum allowed size is {maxSizeBytes}, but the supplied file is of length {fileListEntry.Size}."); + } + + var result = new MemoryStream(); + await sourceData.CopyToAsync(result); + result.Seek(0, SeekOrigin.Begin); + return result; + } + } +}