Implemented download service

This commit is contained in:
2024-12-10 19:52:14 +01:00
parent 150a18cc0b
commit 75cefea4fa
4 changed files with 63 additions and 1 deletions

View File

@@ -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));
}

View File

@@ -101,6 +101,7 @@ public class Startup
);
WebAssemblyHostBuilder.Services.AddScoped<WindowService>();
WebAssemblyHostBuilder.Services.AddScoped<DownloadService>();
WebAssemblyHostBuilder.Services.AddMoonCoreBlazorTailwind();
WebAssemblyHostBuilder.Services.AddScoped<LocalStorageService>();

View File

@@ -1,5 +1,19 @@
@page "/admin"
@using Moonlight.Client.Services
@inject DownloadService DownloadService
<WButton OnClick="OnClick">Test DownloadService</WButton>
@code
{
private async Task OnClick(WButton _)
{
await DownloadService.DownloadString("test.txt", "Download seems to be working");
}
}
@*
@using ApexCharts
<div class="card max-w-md">
@@ -181,4 +195,4 @@
}
}
}*@

View File

@@ -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);
}
}
};