Lab 6 - Upload File in ASP .Net Core
Lab 6 - Upload File in ASP .Net Core
Net Core
Prerequisites
4. Right click the FileUpload folder. Select Add > View. Name the Razor Page as
index.cshtml.
<div class="row">
<section>
<form method="post" enctype="multipart/form-data"
asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form>
</section>
</div>
6. Right click the Controller folder. Select Add > Controller. Choose MVC
Controller-Empty.
8. Select Views > Shared > _LoginPartial.cshtml. Add the below <li></li> sentences
into the page.
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="FileUpload" asp-
action="Index">File Upload</a>
</li>
2. Add the below line inside the public class FileUploadController : Controller{}.
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
return RedirectToAction("Index");
}
3. To receive multiple files, modify the post() method by following the below code.
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
var filePath = ""; string fileContents = null;
int i = 1;
foreach (var formFile in files)
{
if (formFile.ContentType.ToLower() != "text/plain") //not text file..
{
return BadRequest("The " + formFile.FileName + " unable to upload
because uploaded file must be a text file");
}
if (formFile.Length == 0)
{
return BadRequest("The " + formFile.FileName + "file is empty content!");
}
else if (formFile.Length > 1048576)
{
return BadRequest("The " + formFile.FileName + "file is exceed 1 MB !");
}
else
{
if (formFile.Length > 0)
{
filePath = "C:\\Users\\mienmay\\Desktop\\Testupload"+ i +".txt";
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
using (var reader = new StreamReader(formFile.OpenReadStream(),
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,
throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true))
{
fileContents = fileContents + await reader.ReadToEndAsync();
}
}
i++;
}
return RedirectToAction("Index", "FileUpload", new { @contents = fileContents });
}
4. Now, to show the file contents in a message box, you can modify the Index()
method.
public IActionResult Index(string contents)
{
ViewBag.content = contents;
return View();
}
Summary:
In this tutorial, we learned how to build an upload file page in the system. Besides, we also
learnt how to read the contents from a file and upload the file to the specific folder.