Я использую загрузку файлов с помощью грязи
Код: Выделить всё
Select Photos
Код: Выделить всё
public async Task UploadPhotosAsync(IReadOnlyList 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);
}
Код: Выделить всё
public async Task 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(
await httpResponse.Content.ReadAsStringAsync()) : null;
return httpResponse.IsSuccessStatusCode ? JsonConvert.DeserializeObject(
await httpResponse.Content.ReadAsStringAsync()) : null;
}
catch(Exception ex)
{
return null;
}
}
Код: Выделить всё
[HttpPost("upload-photos")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
public async Task UploadPhotos(string year, string eventName, [FromForm] List 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}'." });
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... nd-project
Мобильная версия