From 8369d0617a617fd107aa268ec1f70143651750a7 Mon Sep 17 00:00:00 2001 From: Jamie D Date: Wed, 29 Apr 2020 12:26:50 +0100 Subject: [PATCH] Adding ToDataUrlAsync extension method --- BlazorInputFile/FileListEntryExtensions.cs | 27 ++++++++++++++++++++++ samples/Sample.Core/Pages/ImageFile.razor | 8 ++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/BlazorInputFile/FileListEntryExtensions.cs b/BlazorInputFile/FileListEntryExtensions.cs index f2a4657..67327ae 100644 --- a/BlazorInputFile/FileListEntryExtensions.cs +++ b/BlazorInputFile/FileListEntryExtensions.cs @@ -34,5 +34,32 @@ public static async Task ReadAllAsync(this IFileListEntry fileList result.Seek(0, SeekOrigin.Begin); return result; } + + /// + /// Reads the entire uploaded file into a base64 encoded string. 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. Default max 5mb + /// + /// The . + /// The maximum amount of data to accept. + /// + public static async Task ToDataUrlAsync(this IFileListEntry fileListEntry, int maxSizeBytes = 5 * 1024 * 1024) + { + if (fileListEntry is null) + { + throw new ArgumentNullException(nameof(fileListEntry)); + } + + 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}."); + } + + using var result = new MemoryStream(); + await sourceData.CopyToAsync(result); + return $"data:{fileListEntry.Type};base64, { Convert.ToBase64String(result.ToArray())}"; + } } } diff --git a/samples/Sample.Core/Pages/ImageFile.razor b/samples/Sample.Core/Pages/ImageFile.razor index a165fcb..ae52154 100644 --- a/samples/Sample.Core/Pages/ImageFile.razor +++ b/samples/Sample.Core/Pages/ImageFile.razor @@ -25,13 +25,9 @@ // Load as an image file in memory var format = "image/jpeg"; var imageFile = await rawFile.ToImageFileAsync(format, 640, 480); - var ms = new MemoryStream(); - await imageFile.Data.CopyToAsync(ms); - // Make a data URL so we can display it - imageDataUri = $"data:{format};base64,{Convert.ToBase64String(ms.ToArray())}"; - - status = $"Finished loading {ms.Length} bytes from {imageFile.Name}"; + imageDataUri = await imageFile.ToDataUrlAsync(); + status = $"Finished loading {imageFile.Data.Length} bytes from {imageFile.Name}"; } } }