Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C# I'm having trouble writing the code to download the page.

lingo57

Coder
Hello,

I'm trying to make an app that converts image format to SVG.
I am having trouble writing the code to download the image.
Please inform me.

Code:
    private void DownloadSvg()
{
    byte[] svgBytes = Encoding.UTF8.GetBytes(svgContent);
    var fileName = "convertedImage.svg";

    var base64 = Convert.ToBase64String(svgBytes);
    var dataUrl = $"data:image/svg+xml;base64,{base64}";

    NavigationManager.NavigateTo(dataUrl, true);
}

thanks,
 
Should you use "download" attribute instead of "data" ?

Fix
Code:
var dataUrl = $"data:image/svg+xml;base64,{base64}";
as
Code:
var dataUrl = $"download:image/svg+xml;base64,{base64}";
 
Or you can try this... (I didn't test it but let me know if it worked).

C#:
private void DownloadSvg()

{

    byte[] svgBytes = Encoding.UTF8.GetBytes(svgContent);

    var fileName = "convertedImage.svg";

    var base64 = Convert.ToBase64String(svgBytes);

    var dataUrl = $"data:image/svg+xml;base64,{base64}";

    var link = new ElementReference();

    link.SetAttribute("href", dataUrl);

    link.SetAttribute("download", fileName);

    document.Body.AppendChild(link);

    link.Click();

    document.Body.RemoveChild(link);

}
 
Or you can try this... (I didn't test it but let me know if it worked).

Unfortunately, this answer is wrong.

Explanation:
  1. Use a third-party library: Some libraries extend the functionality of ElementReference with additional methods. If you're using such a library, make sure it's properly referenced and that you have the necessary using directives.

Should you use "download" attribute instead of "data" ?
This is not working.

I have provided the entire code below to understand the code clearly.

Code:
@page "/"
@using System.Drawing
@using System.Drawing.Imaging
@using System.IO
@using System.Threading.Tasks
@using Microsoft.AspNetCore.Components.Forms
@using System.Text
@using Microsoft.AspNetCore.Mvc
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@inject NavigationManager NavigationManager
@using System
@using System.Net
@* @using Microsoft.AspNetCore.Mvc
@using Claue3_Haiko *@






<h3>Bitmap to SVG Converter</h3>

<InputFile OnChange="@HandleFileUploadAsync" />

@* progress-bar *@

@if (isConverting)
{
    <div class="progress mt-3">
        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
    </div>
}


@if (svgContent != null)
{
    <div>
        <h4>Generated SVG:</h4>
        <div>@((MarkupString)svgContent)</div>
    </div>

    <div>

        <button class="btn btn-primary mt-3" @onclick="DownloadSvg">Download SVG</button>
    </div>
}

@code {
    private string svgContent = null!;
    private bool isConverting = false;



    // uploading the image

    private async Task HandleFileUploadAsync(InputFileChangeEventArgs e)
    {
        var file = e.GetMultipleFiles(1).FirstOrDefault();
        if (file != null)
        {
            isConverting = true;
            StateHasChanged();


            using var stream = new MemoryStream();
            await file.OpenReadStream().CopyToAsync(stream);
            stream.Seek(0, SeekOrigin.Begin);

            var bitmap = new Bitmap(stream);
            svgContent = ConvertBitmapToSvg(bitmap);

            isConverting = false;
            StateHasChanged();

        }
    }

    //converting bitmap to svg

    private string ConvertBitmapToSvg(Bitmap bitmap)
    {
        var width = bitmap.Width;
        var height = bitmap.Height;

        var svg = new StringBuilder();
        svg.AppendLine($"<svg width='{width}' height='{height}' xmlns='http://www.w3.org/2000/svg'>");

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                var color = bitmap.GetPixel(x, y);
                var hexColor = $"#{color.R:X2}{color.G:X2}{color.B:X2}";
                svg.AppendLine($"<rect x='{x}' y='{y}' width='1' height='1' fill='{hexColor}' />");
            }
        }

        svg.AppendLine("</svg>");
        return svg.ToString();
    }

    
    
    // Downloading the svg image

    private void DownloadSvg()
{
    byte[] svgBytes = Encoding.UTF8.GetBytes(svgContent);
    var fileName = "convertedImage.svg";

    var base64 = Convert.ToBase64String(svgBytes);
    var dataUrl = $"data:image/svg+xml;base64,{base64}";

    NavigationManager.NavigateTo(dataUrl, true);
}



}
 
Ok, thanks for providing full code. It helps out a bit.
NavigationManager.NavigateTo this does not support downloading if i do remember correctly.

You need to add some javascript to your index.html (I assume you are goin with BLazor here)
Code:
<script>
    function downloadFile(fileName, base64Data) {
        const link = document.createElement('a');
        link.href = 'data:image/svg+xml;base64,' + base64Data;
        link.download = fileName;
        document.body.appendChild(link);
        link,click();
        document.body.removeChild(link);
    }
</scritp>

Oh man. Way too long since i tested these and to be honest, i cant remember anymore how it went.

But you need that javascript (after you bug fixed it since i did not test it) and i think you need to adjust your current code aswell to make component calling the javascript properly.

But i have to give the turn to speak to someone who is more familiar with this.
 
I implemented this code, but the JavaScript file throws an exception.

Code:
<body>
    //.....
    <script src="_framework/blazor.server.js"></script>
    <script>
        function triggerDownload(dataUrl, fileName) {
            const link = document.createElement('a');
        link.href = dataUrl;
        link.download = fileName;
        link.click();
        }
    </script>
</body>

blazor1.png
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom