-
Notifications
You must be signed in to change notification settings - Fork 62
Upload files to an asp.net core mvc controller
Tor edited this page Sep 10, 2019
·
3 revisions
This is an example how to consume the filestreams produced by the library in an mvc project.
Upload.razor
@page "/UploadMvc"
@inject IFileReaderService fileReaderService
@inject HttpClient HttpClient
<h3>Upload multiple</h3>
<input type="file" multiple @ref=inputElement />
<button @onclick="UploadFiles">Upload</button>
<br /><pre>@debug</pre>
@code {
string debug;
ElementReference inputElement;
IFileReaderRef fileReaderReference;
protected override void OnAfterRender(bool isFirstRender)
{
fileReaderReference = fileReaderService.CreateReference(inputElement);
}
public async Task UploadFiles()
{
var multipartFormDataContent = new MultipartFormDataContent();
foreach (var file in await fileReaderReference.EnumerateFilesAsync())
{
multipartFormDataContent.Add(
new StreamContent(await file.OpenReadAsync(), 8192),
"files",
(await file.ReadFileInfoAsync()).Name);
}
var res = await HttpClient.PostAsync(requestUri: "https://myupload.website/api/upload/files",
content: multipartFormDataContent);
debug = await res.Content.ReadAsStringAsync();
}
}
UploadController.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MyFileUploadApplication.Controllers
{
[Route("api/[controller]")]
[ApiController]
[EnableCors()]
public class UploadController : ControllerBase
{
[HttpPost("files"), DisableRequestSizeLimit]
public async Task<IActionResult> UploadFiles(List<IFormFile> files)
{
var result = files.Select(file => new { file.FileName, file.Length }).ToList();
return Ok(result);
}
}
}