How to upload file in ASP.NET Core MVC, File uploading concept in .NET core MVC:-
It is used to upload any external content such as audio, video, text and doc file under project.
Microsoft provide IFormFile class to handle file uploading operation
Step by Step Implementation
1) Create Project
2) Create FileUpload.cs class under Models folder
public class FileUpload
{
public IFormFile FormFile { set; get; }
}
3) Create FileUploadingController Class
using Microsoft.AspNetCore.Mvc;
using CodeFirstExample.Models;
using Microsoft.Extensions.Hosting.Internal;
namespace CodeFirstExample.Controllers
{
public class FileUploadController : Controller
{
private IWebHostEnvironment Environment;
public FileUploadController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View(new FileUpload());
}
[HttpPost]
public IActionResult Index(FileUpload obj)
{
var uniqueFileName = GetUniqueFileName(obj.FormFile.FileName);
var uploads = Path.Combine(Environment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
obj.FormFile.CopyTo(new FileStream(filePath, FileMode.Create));
ViewBag.data = uniqueFileName;
return View("showfile");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
}
POST Answer of Questions and ASK to Doubt