Skip to content

Commit

Permalink
Add ReadAllAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
SteveSandersonMS committed Sep 24, 2019
1 parent 075a154 commit 617b655
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion BlazorInputFile/BlazorInputFile.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
<RazorLangVersion>3.0</RazorLangVersion>
<LangVersion>preview</LangVersion>
<PackageVersion>0.1.0-preview</PackageVersion>
<PackageVersion>0.1.0-preview-00002</PackageVersion>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
</PropertyGroup>

Expand Down
38 changes: 38 additions & 0 deletions BlazorInputFile/FileListEntryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.IO;
using System.Threading.Tasks;

namespace BlazorInputFile
{
public static class FileListEntryExtensions
{
/// <summary>
/// Reads the entire uploaded file into a <see cref="MemoryStream"/>. This will allocate
/// however much memory is needed to hold the entire file, or will throw if the client
/// tries to supply more than <paramref name="maxSizeBytes"/> bytes. Be careful not to
/// let clients allocate too much memory on the server.
/// </summary>
/// <param name="fileListEntry">The <see cref="IFileListEntry"/>.</param>
/// <param name="maxSizeBytes">The maximum amount of data to accept.</param>
public static async Task<MemoryStream> 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;
}
}
}

0 comments on commit 617b655

Please sign in to comment.