Skip to content
This repository was archived by the owner on May 5, 2021. It is now read-only.

Adding ToDataUrlAsync extension method #29

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions BlazorInputFile/FileListEntryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,32 @@ public static async Task<MemoryStream> ReadAllAsync(this IFileListEntry fileList
result.Seek(0, SeekOrigin.Begin);
return result;
}

/// <summary>
/// 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 <paramref name="maxSizeBytes"/> bytes. Be careful not to
/// let clients allocate too much memory on the server. Default max 5mb
/// </summary>
/// <param name="fileListEntry">The <see cref="IFileListEntry"/>.</param>
/// <param name="maxSizeBytes">The maximum amount of data to accept.</param>
/// <returns></returns>
public static async Task<string> 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())}";
}
}
}
8 changes: 2 additions & 6 deletions samples/Sample.Core/Pages/ImageFile.razor
Original file line number Diff line number Diff line change
Expand Up @@ -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}";
}
}
}