Radzen Upload - Unable to read file

Hello,

I am trying to upload a file with RadzenUpload (Client side), but I am always getting the error "Object reference not set to an instance of an object" when I execute:

var stream = file.OpenReadStream (maxFileSize);

The file exists, the variable file is filled....

This was the code that is on the online demo, that I am also using:

    void OnClientChange(UploadChangeEventArgs args)
    {
        console.Log($"Client-side upload changed");

        foreach (var file in args.Files)
        {
            console.Log($"File: {file.Name} / {file.Size} bytes");

            try
            {
                long maxFileSize = 10 * 1024 * 1024;
                // read file
                var stream = file.OpenReadStream(maxFileSize);
                stream.Close();
            }
            catch (Exception ex)
            {
                console.Log($"Client-side file read error: {ex.Message}");
            }
        }
    }

Make sure you are using latest version of Radzen.Blazor. Here is what I see using our demos:

Hello Enchev, thank you for the answer!

I have upgraded from Radzen 5.1 to Radzen 5.3 and I still get the error....
Could it be because I am using a Server Blazor project? Should work the same...

image

The screenshot I've posted is from our demos running as Blazor server application.

Maybe something on the design?

<RadzenCard Variant="Variant.Outlined">
    <RadzenAccordion>
        <Items>
            <RadzenAccordionItem Text="Excel Import" Icon="system_update_alt" CollapseTitle="Collapse ExcelImport."
                                 ExpandTitle="Expand Excel Import." CollapseAriaLabel="Collapse Excel Import."
                                 ExpandAriaLabel="Expand Excel Import.">
                <RadzenRow JustifyContent="JustifyContent.End" AlignItems="AlignItems.Start" Gap="4px">
                    <RadzenColumn Size="12" SizeMD="9" class="rz-text-align-right rz-p-0" style="height: 100%;">
                        <RadzenUpload id="ddUpload" @ref="uploadDD"
                                      ChooseText="Drag and drop here or click to choose file"
                                      Auto="false"
                                      Multiple="false"
                                      Url="upload/restockpoint"
                                      Accept="text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                                      InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "select file" }})"
                                      Change=@OnExcelFileUpload
                                      Style="width: 100%" />
                    </RadzenColumn>
                    <RadzenColumn Size="12" SizeMD="3">
                        <RadzenButton Size="ButtonSize.Medium" Style=" width: 100%;" Text="Import From Excel" Click="@OnImportExcelButtonClick" MouseEnter="@(args => ShowImportInstructionsTooltip(args))" />
                    </RadzenColumn>
                </RadzenRow>
            </RadzenAccordionItem>
        </Items>
    </RadzenAccordion>
</RadzenCard>

The C# code

        protected async Task OnExcelFileUpload (UploadChangeEventArgs args)
        {
            var file = args.Files.FirstOrDefault ();

            if ( file != null )
            {
                // Create a temporary file path in the wwwroot/uploads directory
                var uploadsFolder = Path.Combine (_webHostEnvironment.WebRootPath, "uploads");
                if ( !Directory.Exists (uploadsFolder) )
                {
                    Directory.CreateDirectory (uploadsFolder);
                }

                long maxFileSize = 10 * 1024 * 1024;
                // read file
                var stream2 = file.OpenReadStream (maxFileSize);
                stream2.Close ();
            }
        }

According to your screenshot the Source property of the arguments is null however I'm not aware of how this might happen.

Ok, now I was able to edit the post and add the correct metatag!

Hi @Ricardo_Silva,

I suggest trying one of the following to find the problem:

  1. Start removing components until there is only RadzenUpload or things start working.
  2. Test with the built-in InputFile (which RadzenUpload uses under the hood). It should work however if it too fails there could be some different problem altogether.
  3. Try uploading smaller or different files to see if the situation changes.

I am receiving the exactly same error using the code from the component examples. I have upgraded to the latest 5.3.5. Attempted uploads of different sizes (most images are under 1mb).
Fails on the same "file.OpenReadStream(maxLength)" with the same error.

Not sure what I am missing here.

Hello Dingoace10

Even if the Radzen components are awesome, this one was also not working for me... I tried everything like you. I ended up using the InputFile component from Microsoft.AspNetCore.Components.Forms.InputFile.

<InputFile @ref="fileExcelInputRef" OnChange="OnInputFileChange" class="form-control" accept="text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

The C# code:

private string tempExcelFilePath = "";

protected async Task OnInputFileChange (InputFileChangeEventArgs e)
{
    try
    {
        //Gets the file
        IBrowserFile file = e.GetMultipleFiles ().FirstOrDefault ();

        if ( file != null )
        {
            _notificationsService.ShowBusyDialog ("Uploading file");
            // Save the file to a temporary location
            var uploadsFolder = Path.Combine (_webHostEnvironment.WebRootPath, "uploads");
            if ( !Directory.Exists (uploadsFolder) )
            {
                Directory.CreateDirectory (uploadsFolder);
            }

            tempExcelFilePath = Path.Combine (uploadsFolder, $"{Guid.NewGuid ()}.xlsx");

            await using FileStream fs = new (tempExcelFilePath, FileMode.Create);
            await file.OpenReadStream (maxAllowedSize: 100000000).CopyToAsync (fs);
            fs.Close ();

            _notificationsService.CloseBusyDialog ();

        }
    }
    catch ( Exception ex )
    {
        _notificationsService.CloseBusyDialog ();

        //Delete file after it finishes
        if ( File.Exists (tempExcelFilePath) )
        {
            File.Delete (tempExcelFilePath);
        }
        //CLEAN FILE FIELDS
        tempExcelFilePath = "";
        await _jsRuntime.InvokeVoidAsync ("resetFileInput", fileExcelInputRef.Element);

        _notificationsService.ShowNotificationError ("Error Uploading Excel File", ex.GetException ());
    }

}

protected async Task OnImportExcelButtonClick (MouseEventArgs args)
{
    try
    {
        DbOperationResult result;

        if ( tempExcelFilePath != "" )
        {
            _notificationsService.ShowBusyDialog ("Executing Excel Import");

            // Call your ExcelImporter function
            result = await _excelOperationsProvider.ImportExcelRestockPoints (_applicationStateProvider.CurrentShopifyShopId, tempExcelFilePath);


            _notificationsService.CloseBusyDialog ();

            if ( result.Success )
            {
                await _notificationsService.ShowDialogSuccess ("Excel File Import", "Import completed successfully.");
            }
            else
            {
                await _notificationsService.ShowDialogError ("Error Importing Excel File", result.Error);
            }

            //RELOADS RECORDS
            _isLoadingRestockPointProducts = true;
            _settingsVM = await _unitOfWork.ShopifyApp.Settings.SettingsReloadAsync (_applicationStateProvider.CurrentShopifyShopId, true, false);
            _isLoadingRestockPointProducts = false;
            await InvokeAsync (StateHasChanged);

            //DELETE FILE
            if ( File.Exists (tempExcelFilePath) )
            {
                File.Delete (tempExcelFilePath);
            }
            //CLEAN FILE FIELDS
            tempExcelFilePath = "";
            await _jsRuntime.InvokeVoidAsync ("resetFileInput", fileExcelInputRef.Element);
        }
        else
        {
            await _notificationsService.ShowDialogWarning ("Excel File Import", "Please upload a file before importing.");
        }

    }
    catch ( Exception ex )
    {
        //Delete file after it finishes
        if ( File.Exists (tempExcelFilePath) )
        {
            File.Delete (tempExcelFilePath);
        }
        //CLEAN FILE FIELDS
        tempExcelFilePath = "";
        await _jsRuntime.InvokeVoidAsync ("resetFileInput", fileExcelInputRef.Element);

        _notificationsService.CloseBusyDialog ();
        await InvokeAsync (StateHasChanged);
        _notificationsService.ShowNotificationError ("Error Importing Excel File", ex.GetException ());
    }
}

Thanks for the heads up! Thought I was going crazy! I ended up using the InputFile also for a temp solution to get things working. Was hoping that someone from Radzen may respond with a solution.
Thanks for the code snippet!

We can't reproduce this in our tests. Until we do we can't propose a solution. Tried with our online demos, a new app (server and wasm) - no luck. The code from the demo works without problem. If you need a response from us provide a reproduction.

I am having this same problem. The "source" property of the file, which is supposed to contain the IBrowserFile content and is required for the OpenReadStream method, is NULL. I do not understand why. The file name and size values are populated but the source is NULL. Of course this makes the control unusable.

If any Radzen folks could provide shine some light on a solution to this issue that would be great. I really prefer to use this over a native solution.