Rositsa Ruseva

Rositsa Ruseva

  • 1.2k
  • 218
  • 34.4k

Blazor Server: Add product with images issue

Mar 28 2024 5:14 PM

Hello,
I am trying to add a product with images but I always get such an error:
System.IO.IOException: Supplied file with size 951661 bytes exceeds the maximum of 512000 bytes.

 

I have tried to configure a limit:

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 10485760; // 10MB
});

In debug such exception is thrown in line 10:

private async Task AddProduct()
    {
        // Create the product
        await ((Task<Microsoft.AspNetCore.Mvc.IActionResult>)ProductController.CreateProduct(product));

        // Upload images
        foreach (var file in selectedFiles)
        {
            // Convert the file to byte array
            using (var stream = file.OpenReadStream())
            {
                using (var memoryStream = new MemoryStream())
                {
                    await stream.CopyToAsync(memoryStream);
                    var imageData = memoryStream.ToArray();

                    // Create ProductImages model and assign image data
                    var productImage = new ProductImages
                        {
                            ImageData = imageData
                        };

                    // Link the image to the product and create it
                    productImage.ProductId = product.ProductId;
                    await ((Task<Microsoft.AspNetCore.Mvc.IActionResult>)ProductImageController.CreateProductImage(productImage));
                }
            }
        }

        // Redirect to products page after adding the product
        NavigationManager.NavigateTo("/products");
    }

The idea is to be able to add a product with multiple images.
How could I fix this and to be able to add a product with images?


Answers (1)