Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Problem in uplodaing files to API through Blazor Frontend project

$
0
0

I have an issue when i try to pass files from my frontend to api projecti am using mud blazor file upload

<MudFileUpload T="IReadOnlyList<IBrowserFile>"               Accept=".png, .jpg"               FilesChanged="UploadPhotosAsync"               MaximumFileCount="100"               Class="me-1"               Disabled="@(IsUploadingForbidden())"><ActivatorContent><MudButton Disabled="@(IsUploadingForbidden())"                   Variant="Variant.Filled"                   Color="Color.Success"                   StartIcon="@Icons.Material.Filled.CloudUpload">            Select Photos</MudButton></ActivatorContent></MudFileUpload>

my frontend code:

    public async Task UploadPhotosAsync(IReadOnlyList<IBrowserFile> browserFiles)    {     using var content = new MultipartFormDataContent();     foreach (var browserFile in browserFiles)     {         var fileStream = browserFile.OpenReadStream(maxAllowedSize: 10 * 1024 *     1024); // e.g., 10 MB limit         var streamContent = new StreamContent(fileStream);         streamContent.Headers.ContentType = new MediaTypeHeaderValue(browserFile.ContentType);         streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")         {             FileName = browserFile.Name,             Name = "files" // This should match the name used in the backend parameter         };         content.Add(streamContent, "files", browserFile.Name);     }     await GalleryService.UploadPhotos(SelectedYear, SelectedEvent, content);     }

my service:

 public async Task<object?> UploadPhotos(string year, string eventName, MultipartFormDataContent files) {     try     {         HttpResponseMessage httpResponse =              await _httpClient.PostAsync($"{RequestBaseUrl}/upload-photos?year={year}&eventName={eventName}", files);         var x = httpResponse.IsSuccessStatusCode ? JsonConvert.DeserializeObject<object>(             await httpResponse.Content.ReadAsStringAsync()) : null;         return httpResponse.IsSuccessStatusCode ? JsonConvert.DeserializeObject<object>(             await httpResponse.Content.ReadAsStringAsync()) : null;     }     catch(Exception ex)      {         return null;     } }

API:

    [HttpPost("upload-photos")]    [ProducesResponseType(200)]    [ProducesResponseType(400)]    public async Task<IActionResult> UploadPhotos(string year, string eventName,     [FromForm] List<IFormFile> files)    {    // Validate inputs    if (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(eventName))    {        return BadRequest("Both year and event name must be provided.");    }    if (files == null || files.Count == 0)    {        return BadRequest("No files provided for upload.");    }    try    {        // Call the service to upload the photos        await galleryService.UploadPhotosAsync(year, eventName, files);    }    catch (Exception ex)    {        // Return a 400 Bad Request with the error message if upload fails        return BadRequest(new { message = ex.Message });    }    // Return a success message after upload    return Ok(new { message = $"Files uploaded successfully to the event '{eventName}'    in the year '{year}'." });    }

I have tried modifying header and using stream and problem is still there, when i call the api with files it just doesnt dont anything, i tried in postman and it works fine with any number of files, sometimes my above code works when i send only 1 file, the API breakpoint of UploadPhotos hit, I dont know what is happening


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>