Upload File MVC Core

.Net Core 2x

Upload and save some file.

FileUploadViewModel

1
2
3
4
public string Foo { get; set; }

[Display(Name = "Some File")]
public List<IFormFile> FormFiles { get; set; }

FileUploadController

1
2
3
4
5
6
7
8
9
10
11
12
13
// POST: FileUpload/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PackageType,FormFiles")] FileUploadViewModel fileUploadViewModel)
{
if (ModelState.IsValid)
{
var postedFile = fileUploadViewModel.FormFiles[0];

using (var memoryStream = new MemoryStream())
{
postedFile.CopyTo(memoryStream);
...

View Create.cshtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<form asp-action="Create" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="Foo" class="control-label"></label>
<input asp-for="Foo" class="form-control" />
<span asp-validation-for="PackageType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="FormFiles" class="control-label"></label>
<input asp-for="FormFiles" type="file" multiple>
<span asp-validation-for="FormFiles" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-primary" />
</div>
</form>

References