razor page upload file method code example
Example: asp.net core razor pages upload file
Upload and save to folder link
The following code features a very simple page called UploadFile.cshtml with a form for uploading a file:
@page
@model UploadFileModel
@{
}
<form method="post" enctype="multipart/form-data">
<input type="file" asp-for="Upload" />
<input type="submit" />
</form>
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.IO;
using System.Threading.Tasks;
namespace RazorPagesForms.Pages
{
public class UploadFileModel : PageModel
{
private IHostingEnvironment _environment;
public UploadFileModel(IHostingEnvironment environment)
{
_environment = environment;
}
[BindProperty]
public IFormFile Upload { get; set; }
public async Task OnPostAsync()
{
var file = Path.Combine(_environment.ContentRootPath, "uploads", Upload.FileName);
using (var fileStream = new FileStream(file, FileMode.Create))
{
await Upload.CopyToAsync(fileStream);
}
}
}
}