I created One application, When I try to upload more then 30 MB of images, I am unable to save them to the network drive. I will Save them into network drive only when user click on the submit button. But right now, The upload fails, and I receive an error: "Request Entity Too Large." How can I resolve this issue?
My code
private async Task HandleImageSelection(InputFileChangeEventArgs e)
{ selectedImages.Clear();
if (string.IsNullOrEmpty(selectedFolder))
{
Snackbar.Add("Please select a folder first.", Severity.Warning);
return;
}
// Set the constraints
const int maxImagesAllowed = 20; // Maximum number of images
const long maxTotalSize = 100 * 1024 * 1024; // 100 MB (Total)
const long maxAllowedSize = 100 * 1024 * 1024; // 100 MB per file (not needed, since total size is already 100 MB)
var selectedFiles = e.GetMultipleFiles(maxImagesAllowed); // Limit to 20 images
long totalSize = selectedFiles.Sum(file => file.Size);
// Check if the total size exceeds the limit
if (totalSize > maxTotalSize)
{
Snackbar.Add($"The total size of selected images exceeds the limit of 100 MB. Current size: {Math.Round((double)totalSize / (1024 * 1024), 2)} MB.", Severity.Error);
return;
}
foreach (var file in selectedFiles)
{
// Check if the file is an image
if (!file.ContentType.StartsWith("image/"))
{
Snackbar.Add($"File '{file.Name}' is not a valid image. Please select only image files.", Severity.Warning);
continue;
}
try
{
using var stream = file.OpenReadStream(maxAllowedSize);
var buffer = new byte[file.Size];
await stream.ReadAsync(buffer, 0, (int)file.Size);
var base64Data = Convert.ToBase64String(buffer);
// Add to the list of selected images
selectedImages.Add(new ImagePreview
{
PreviewUrl = $"data:{file.ContentType};base64,{base64Data}",
File = file,
Base64Data = base64Data
});
}
catch (Exception ex)
{
Snackbar.Add($"Error loading file '{file.Name}': {ex.Message}", Severity.Error);
}
}
SelectedFiles = selectedFiles
.Where(file => file.ContentType.StartsWith("image/"))
.ToList();
StatusMessage = $"{SelectedFiles.Count} valid image file(s) selected. Total size: {Math.Round((double)totalSize / (1024 * 1024), 2)} MB.";
} upload Image code:
private async Task UploadFiles(string combinedFolderPath)
{
if (string.IsNullOrWhiteSpace(combinedFolderPath))
{
Snackbar.Add("Please select a folder!", Severity.Warning);
return;
}
if (SelectedFiles == null || !SelectedFiles.Any())
{
Snackbar.Add("No files selected!", Severity.Warning);
return;
}
// Check file size limits
foreach (var file in SelectedFiles)
{
if (file.Size > MaxFileSize)
{
Snackbar.Add($"File {file.Name} exceeds the size limit of 100 MB.", Severity.Warning);
return;
}
}
try
{
using var content = new MultipartFormDataContent();
content.Add(new StringContent(combinedFolderPath), "folderPath");
foreach (var file in SelectedFiles)
{
var streamContent = new StreamContent(file.OpenReadStream(MaxFileSize));
content.Add(streamContent, "files", file.Name);
}
var response = await HttpClient.PostAsync(ApiConstants.UploadImage, content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var filePaths = JsonSerializer.Deserialize<List<string>>(responseContent);
for (int i = 0; i < selectedImages.Count; i++)
{
selectedImages[i].FilePath = filePaths[i];
}
// Snackbar.Add("Images uploaded successfully!", Severity.Success);
}
else
{
Snackbar.Add($"Error: {response.ReasonPhrase}", Severity.Error);
}
}
catch (Exception ex)
{
Snackbar.Add($"Upload failed: {ex.Message}", Severity.Error);
}
}
submit code: ` private async Task SubmitForm()
{
if (string.IsNullOrWhiteSpace(maagimage.ProjectKent))
{
Snackbar.Add("Please enter a valid project name.", Severity.Error);
return;
}
if (string.IsNullOrWhiteSpace(selectedFolder))
{
Snackbar.Add("Please select a folder location.", Severity.Warning);
return;
}
// Upload images first
// await UploadFiles();
// Create project folder in the selected location
await CreateProjectFolder();
var userData = await localStorage.GetItemAsync<UserPagesAndRouter>("UserData");
currentUsername = userData?.UserName;
if (string.IsNullOrEmpty(maagimage.ProjectKent) || string.IsNullOrEmpty(maagimage.Department))
{
Snackbar.Add("Please fill in all the required fields.", Severity.Error);
return;
}
if (selectedImages.Count == 0)
{
Snackbar.Add("No images selected for submission.", Severity.Warning);
return;
}
// Prepare the form data to send to the API
var formData = new MaagAmericansImage
{
Location = maagimage.Location,
Department = maagimage.Department,
Username = currentUsername, // Set the current user, or pass as needed
Date = DateTime.Now, // Set the current date
ProjectKent = maagimage.ProjectKent,
Images = selectedImages.Select(img => new Imagedata
{
ImageFilePath = img.FilePath // Use the saved file path
}).ToList()
};
try
{
var response = await HttpClient.PostAsJsonAsync(ApiConstants.AddimageDetails, formData);
if (response.IsSuccessStatusCode)
{
// Snackbar.Add("Your Photos have been Uploaded Successfully!", Severity.Success);
// Show success dialog instead of Snackbar
var dialog = DialogService.Show<SuccessDialog>("", new DialogParameters { { "Message", "Your Photos have been Uploaded Successfully!" } });
var result = await dialog.Result;
ClearFormData();
// Additional logic after dialog closes (if needed)
}
else
{
var errorMessage = await response.Content.ReadAsStringAsync();
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest && errorMessage.Contains("The ImageFilePath field is required."))
{
//Snackbar.Add("Project Folder is not match with the selected folder.", Severity.Error);
}
else
{
Snackbar.Add($"Submission failed: {errorMessage}", Severity.Error);
}
}
}
catch (Exception ex)
{
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
}
}
`
According to your description and codes, it seems the error is thrown at this line Snackbar.Add($"Error: {response.ReasonPhrase}", Severity.Error);
and when you send the request to the web api.
I suggest you could modify your web api project to allow the big request body.
More details, you could refer to below codes:
1.Set the request body limit inside the program.cs:
var app = builder.Build();
builder.Services.Configure<FormOptions>(options => {
options.MultipartBodyLengthLimit = int.MaxValue;
});
....
2.Disable the request size limit
[HttpPost]
[DisableRequestSizeLimit]
public IActionResult Uploadimage(IFormFile formFile) {
return Ok();
}