How to trigger Blazor InputFile and pass it a file

Isaac 6 Reputation points
2020-12-07T17:10:40.917+00:00

I'm trying to save an audio file I got using the MediaRecorder API . I am able to download my file to my hard disk as well as upload it to my Blazor server app using the InputFile component. That part works.

However, what I'd like to ultimately do is skip those UI interactions and instead of downloading the file just to re-upload it, just upload it when I click on the download button which I will be renaming to upload.

Here's the code in my handler attached to the <InputFile>

async Task OnInputFileChange(InputFileChangeEventArgs e)
    {

        Stream stream = e.File.OpenReadStream();

        var path = $"{env.WebRootPath}\\uploads\\{e.File.Name}";
        FileStream fs = File.Create(path);
        await stream.CopyToAsync(fs);
        stream.Close();
        fs.Close();
        Message = $"{e.File.Name} file(s) uploaded on server";
    }

Is it possible to trigger the InputFile component and pass it either the url for the file and have it post to the Blazor server app?

If not, is there a different way I should be thinking of this problem?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,562 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Isaac 6 Reputation points
    2020-12-12T04:31:24.537+00:00

    I figured out one way to do it. I converted my Blob to a base64 string.

    //JavaScript to convert Blob to base64 string

    const blobToBase64 = blob => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        return new Promise(resolve => {
            reader.onloadend = () => {
                resolve(reader.result.substr(reader.result.indexOf(',') + 1));
            };
        });
    };
    

    Then passed the base64 string in as a parameter of type byte array as shown below.

    // My C# method in my Blazor app

    [JSInvokable("UploadFile")]
    public async Task UploadFile(byte[] recording)
    {
        MemoryStream e = new MemoryStream(recording);
    
        var path = $"{env.WebRootPath}\\uploads\\file.ogg";
        FileStream fs = File.Create(path);
        await e.CopyToAsync(fs);
        e.Close();
        fs.Close();
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.