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(options =>
{
options.MultipartBodyLengthLimit = 10485760; // 10MB
});
In debug such exception is thrown in line 10:
private async Task AddProduct()
{
// Create the product
await ((Task)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)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?
Naimish MakwanaPosted Mar 29, 2024, 4:48 AM
The error message indicates that the size of the file you’re trying to upload exceeds the maximum allowed size. You’ve correctly identified that you need to increase the maximum allowed size for file uploads, and you’ve attempted to do so by configuring
FormOptions.MultipartBodyLengthLimit.However, the error still persists. This could be due to a couple of reasons:
The configuration isn’t applied: Ensure that the configuration code is placed in the correct location. It should be in the
ConfigureServicesmethod in theStartup.csfile.Another limit is being hit: ASP.NET Core has multiple levels of safeguards to prevent excessive resource consumption. If increasing
MultipartBodyLengthLimitdoesn’t work, you might be hitting one of the other limits. For example,Kestrel(the default web server for ASP.NET Core) has its own limits. You can try increasing Kestrel’s maximum request body size limit:And in your
Program.csfile:Remember to adjust these values according to your needs. Be aware that allowing larger files will increase memory usage for your app.
Thanks