Roland Deschain
Roland Deschain

Reputation: 2880

blazor server file upload silently crashes server

I'm testing image upload on my blazor server application. For this, my .razor component looks like this:

@page "/uploadtest"

<h1>Upload Example</h1>
<AuthorizeView>
    <Authorized>
        <p>A simple example with a model, which can upload images</p>
        <label>
            Load Images:
            <InputFile OnChange="@UploadImages" multiple accept=".jpg,.jpeg,.png" />
        </label>

    </Authorized>
    <NotAuthorized>
        <p>To use this application, please <a href="Identity/Account/Login">log in</a> or <a href="Identity/Account/Register">register</a> a new account! </p>
    </NotAuthorized>
</AuthorizeView>

I put the code-behind in a separate .razor.cs file, the class looks like this:

public partial class UploadExample: ComponentBase
{ 
    #region Protected Properties
    [Inject]
    protected AuthenticationStateProvider AuthenticationStateProvider { get; private set; }

    [Inject]
    protected IWebHostEnvironment WebHostEnvironment { get; private set; }
    #endregion

    #region Public Methods
    /// <summary>
    /// File upload
    /// Only images of type .jpg and png are allowed here.
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    protected async Task UploadImages(InputFileChangeEventArgs ifc)
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            try
            {
                string userId = user.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;
                string currentTime = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
                string path = Path.Combine(WebHostEnvironment.WebRootPath, $@"UserData/{userId}/UploadTest/{currentTime}");
                Directory.CreateDirectory(path);
                var files = ifc.GetMultipleFiles();
                foreach (var file in files)
                {
                    var filePath = Path.Combine(path, file.Name);
                    await using FileStream fs = new(filePath, FileMode.Create);
                    await file.OpenReadStream().CopyToAsync(fs);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    #endregion
}

Here are my issues:

Edit In the Dev-Options of my browser, I get the following error:

Error: Connection disconnected with error 'Error: WebSocket closed with status code: 1006 ().'.

as soon as I select any file for upload. I tested different things (with/without authorization, calling/not calling the UploadImages() functions, etc...)

Upvotes: 4

Views: 4088

Answers (2)

Tangere Apps
Tangere Apps

Reputation: 306

I was getting the same error in Google Chrome running a server-side Blazor project. Inside my appsettings.Development.json, I set all of my logging levels to debug before finally finding this error inside Visual Studio > Output:

Microsoft.AspNetCore.SignalR.HubConnectionHandler: Debug: Error when processing requests.

System.IO.InvalidDataException: The maximum message size of 32768B was exceeded. The message size can be configured in AddHubOptions.
    at Microsoft.AspNetCore.SignalR.HubConnectionHandler`1.DispatchMessagesAsync(HubConnectionContext connection)
    at Microsoft.AspNetCore.SignalR.HubConnectionHandler`1.RunHubAsync(HubConnectionContext connection)

The solution is to go into your Program.cs and add the following hub option:

builder.Services.AddServerSideBlazor().AddHubOptions(options =>
{
    // maximum message size of 2MB
    options.MaximumReceiveMessageSize = 2000000;
});

Here's a sample of my image upload code, which I didn't need to change:

// maximum message size of 2MB
using (Stream stream = args.File.OpenReadStream(2000000))
{
    await using (MemoryStream memoryStream = new MemoryStream())
    {
        await stream.CopyToAsync(memoryStream);

        imageBuffer = memoryStream.ToArray();
    }

    string base64 = Convert.ToBase64String(imageBuffer);
    ...
}

Upvotes: 3

mu88
mu88

Reputation: 5454

I stumbled across that issue: Blazor Server inputfile Crashes with certain Chromium Based Browsers
That sounds pretty much like what you're experiencing, right?

To further proof that theory, please download the following code: https://github.com/mu88/StackOverflow_BlazorServerFileUpload
That's basically a simplified copy of your code which works on my machine in Chrome and Firefox. If you can run that code on your machine in Chrome and Firefox, but not in Brave, I think we can be sure that we found the culprit.

Upvotes: 10

Related Questions