diff --git a/Moonlight.Client/Services/DownloadService.cs b/Moonlight.Client/Services/DownloadService.cs new file mode 100644 index 00000000..df997f13 --- /dev/null +++ b/Moonlight.Client/Services/DownloadService.cs @@ -0,0 +1,34 @@ +using System.Text; +using Microsoft.JSInterop; + +namespace Moonlight.Client.Services; + +public class DownloadService +{ + private readonly IJSRuntime JsRuntime; + + public DownloadService(IJSRuntime jsRuntime) + { + JsRuntime = jsRuntime; + } + + public async Task DownloadStream(string fileName, Stream stream) + { + using var streamRef = new DotNetStreamReference(stream); + + await JsRuntime.InvokeVoidAsync("moonlight.utils.download", fileName, streamRef); + } + + public async Task DownloadBytes(string fileName, byte[] bytes) + { + var ms = new MemoryStream(bytes); + + await DownloadStream(fileName, ms); + + ms.Close(); + await ms.DisposeAsync(); + } + + public async Task DownloadString(string fileName, string content) => + await DownloadBytes(fileName, Encoding.UTF8.GetBytes(content)); +} \ No newline at end of file diff --git a/Moonlight.Client/Startup.cs b/Moonlight.Client/Startup.cs index 06647c77..ef8c22c4 100644 --- a/Moonlight.Client/Startup.cs +++ b/Moonlight.Client/Startup.cs @@ -101,6 +101,7 @@ public class Startup ); WebAssemblyHostBuilder.Services.AddScoped(); + WebAssemblyHostBuilder.Services.AddScoped(); WebAssemblyHostBuilder.Services.AddMoonCoreBlazorTailwind(); WebAssemblyHostBuilder.Services.AddScoped(); diff --git a/Moonlight.Client/UI/Views/Admin/Index.razor b/Moonlight.Client/UI/Views/Admin/Index.razor index b0cb7616..8fa47d90 100644 --- a/Moonlight.Client/UI/Views/Admin/Index.razor +++ b/Moonlight.Client/UI/Views/Admin/Index.razor @@ -1,5 +1,19 @@ @page "/admin" +@using Moonlight.Client.Services +@inject DownloadService DownloadService + +Test DownloadService + +@code +{ + private async Task OnClick(WButton _) + { + await DownloadService.DownloadString("test.txt", "Download seems to be working"); + } +} + +@* @using ApexCharts
@@ -181,4 +195,4 @@ } -} \ No newline at end of file +}*@ \ No newline at end of file diff --git a/Moonlight.Client/wwwroot/js/moonlight.js b/Moonlight.Client/wwwroot/js/moonlight.js index f4a5b4a6..480e6186 100644 --- a/Moonlight.Client/wwwroot/js/moonlight.js +++ b/Moonlight.Client/wwwroot/js/moonlight.js @@ -44,5 +44,18 @@ window.moonlight = { (document.head || document.documentElement).appendChild(scriptElement); } + }, + utils: { + download: async function (fileName, contentStreamReference) { + const arrayBuffer = await contentStreamReference.arrayBuffer(); + const blob = new Blob([arrayBuffer]); + const url = URL.createObjectURL(blob); + const anchorElement = document.createElement('a'); + anchorElement.href = url; + anchorElement.download = fileName ?? ''; + anchorElement.click(); + anchorElement.remove(); + URL.revokeObjectURL(url); + } } }; \ No newline at end of file