Create ASP.NET Core Razor Pages Project
On the Visual Studio, create new ASP.NET Core Web Application project
Select Empty Template
Click Ok button to Finish
wwwroot Folder
Create new folder named wwwroot
Images Folder
Create new folder named images in wwwroot folder.
Configurations
Open Startup.cs file and add new configurations as below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreRazorPagesWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
}
}
}
Create Razor View Imports
Select Views folder and right click to select Add\New Item Menu
Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish
In _ViewImports.cshtml file and TagHelpers library as below:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Create Razor Page
Create new folder named Pages. In this folder, create new Razor Page named Index as below:
Index.cshtml.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.IO;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
public class IndexModel : PageModel
{
private IHostingEnvironment ihostingEnvironment;
public List<string> FileNames { get; set; }
public IndexModel(IHostingEnvironment ihostingEnvironment)
{
this.ihostingEnvironment = ihostingEnvironment;
}
public void OnGet()
{
}
public void OnPost(IFormFile[] photos)
{
if (photos != null && photos.Length > 0)
{
FileNames = new List<string>();
foreach (IFormFile photo in photos)
{
var path = Path.Combine(ihostingEnvironment.WebRootPath, "images", photo.FileName);
var stream = new FileStream(path, FileMode.Create);
photo.CopyToAsync(stream);
FileNames.Add(photo.FileName);
}
}
}
}
}
Index.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-page="Index" enctype="multipart/form-data">
Photos <input type="file" name="photos" multiple="multiple" accept="image/*" />
<br />
<input type="submit" value="Upload" />
@if (Model.FileNames != null && Model.FileNames.Count > 0)
{
<ul>
@foreach (var fileName in Model.FileNames)
{
<li><img src="~/images/@fileName" /></li>
}
</ul>
}
</form>
</body>
</html>
Structure of ASP.NET Core Razor Pages Project
Run Application
Open Index Razor Page with following url: http://localhost:1115
Select multiple image files and click Upload button submit form to OnPost action in Index razor page with following url: http://localhost:1115/
Output