From 00cb290649ae999a1c76e3106d46a366a244eb36 Mon Sep 17 00:00:00 2001 From: "Jade.VAN_BRABANDT" Date: Thu, 14 Dec 2023 13:53:27 +0100 Subject: [PATCH] Feat : Finished CSV export, code might not be clean --- Blazor/Blazor/Pages/Chapters.razor | 2 ++ Blazor/Blazor/Pages/Chapters.razor.cs | 19 +++++++------------ Blazor/Blazor/Pages/Chapters.razor.js | 11 +++++++++++ 3 files changed, 20 insertions(+), 12 deletions(-) create mode 100644 Blazor/Blazor/Pages/Chapters.razor.js diff --git a/Blazor/Blazor/Pages/Chapters.razor b/Blazor/Blazor/Pages/Chapters.razor index 4bdef15..d9df7c8 100644 --- a/Blazor/Blazor/Pages/Chapters.razor +++ b/Blazor/Blazor/Pages/Chapters.razor @@ -12,3 +12,5 @@ + + \ No newline at end of file diff --git a/Blazor/Blazor/Pages/Chapters.razor.cs b/Blazor/Blazor/Pages/Chapters.razor.cs index d577b97..7e481e2 100644 --- a/Blazor/Blazor/Pages/Chapters.razor.cs +++ b/Blazor/Blazor/Pages/Chapters.razor.cs @@ -3,7 +3,7 @@ using Blazored.LocalStorage; using Blazorise.DataGrid; using ChoETL; using Microsoft.AspNetCore.Components; -using System.Reflection.Metadata; +using Microsoft.JSInterop; using System.Text; namespace Blazor.Pages; @@ -25,6 +25,9 @@ public partial class Chapters [Inject] public NavigationManager NavigationManager { get; set; } + [Inject] + public IJSRuntime IJSRuntime { get; set; } + protected override async Task OnAfterRenderAsync(bool firstRender) { // Do not treat this action if is not the first render @@ -75,19 +78,11 @@ public partial class Chapters } } + var sentFile = new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())); - - string path = @"C:\temp\file"; // path to file - using (FileStream fs = File.Create(path)) + using (var streamRef = new DotNetStreamReference(stream: sentFile)) { - // writing data in string - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); - - // writing data in bytes already - byte[] data = new byte[] { 0x0 }; - fs.Write(data, 0, data.Length); + await IJSRuntime.InvokeVoidAsync("downloadFileFromStream", "data.csv", streamRef); } - } } \ No newline at end of file diff --git a/Blazor/Blazor/Pages/Chapters.razor.js b/Blazor/Blazor/Pages/Chapters.razor.js new file mode 100644 index 0000000..37f904d --- /dev/null +++ b/Blazor/Blazor/Pages/Chapters.razor.js @@ -0,0 +1,11 @@ +window.downloadFileFromStream = async (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