File Upload in ASP.NET Core MVC: A Step-by-Step Guide
File uploading is a common feature in web applications, and ASP.NET Core MVC provides a convenient way to implement this functionality. In this blog post, we'll walk through a simple example of file upload in ASP.NET Core MVC using a form, controller, and a dedicated service.
Setting Up the Form
Let's start with the form that users will interact with to upload files. The form uses the Index action in the FileUpload controller. It includes a file input element, and the form is configured to handle file uploads using the enctype="multipart/form-data" attribute.
<form asp-action="Index" asp-controller="FileUpload" class="mb-4 g-3 needs-validation" novalidate autocomplete="off" method="post" enctype="multipart/form-data">
<div class="mb-3 mt-3">
<label for="FileInput" class="form-label">File:</label>
<input type="file" class="form-control" id="FileInput" name="FileInput" required>
<div class="invalid-feedback">
Please provide a file.
</div>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
Creating the FileUploadController
Next, let's take a look at the FileUploadController responsible for handling file uploads. It contains an Index action for rendering the initial view and a corresponding [HttpPost] action to process file uploads.
public class FileUploadController : Controller
{
readonly IFileUploadService _fileUploadService;
public FileUploadController(IFileUploadService fileUploadService)
{
_fileUploadService = fileUploadService;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(IFormFile FileInput)
{
try
{
var uploadedFile = await _fileUploadService.UploadFile(FileInput);
if (!string.IsNullOrEmpty(uploadedFile))
{
ViewBag.Message = $"File Upload Successful. View <a href=UploadedFiles/{uploadedFile} download>File</a>";
}
else
{
ViewBag.Message = "File Upload Failed";
}
}
catch (Exception ex)
{
// Log the exception
Console.WriteLine(ex.Message);
ViewBag.Message = "File Upload Failed";
}
return View();
}
}
Implementing the FileUploadService
Now, let's dive into the FileUploadService that contains the logic for handling file uploads. The service implements the IFileUploadService interface, defining methods for uploading files and generating unique file names.
public interface IFileUploadService
{
Task<string> UploadFile(IFormFile file);
string GetUniqueFileName(string fileName);
}
public class FileUploadService : IFileUploadService
{
public async Task<string> UploadFile(IFormFile fileInput)
{
try
{
string path = string.Empty;
if (fileInput.Length > 0)
{
var uniqueFileName = GetUniqueFileName(fileInput.FileName);
path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "wwwroot/UploadedFiles"));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (var fileStream = new FileStream(Path.Combine(path, uniqueFileName), FileMode.Create))
{
await fileInput.CopyToAsync(fileStream);
}
return uniqueFileName;
}
else
{
return string.Empty;
}
}
catch (Exception ex)
{
throw new Exception("File Upload Failed", ex);
}
}
public string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
var renamedfilename = Guid.NewGuid().ToString() + Path.GetExtension(fileName);
return renamedfilename.Replace(" ", "_");
}
}
Conclusion
In this blog post, we've covered the basics of implementing file upload functionality in an ASP.NET Core MVC application. The provided code demonstrates how to create a form, a controller to handle file uploads, and a service to encapsulate the file upload logic. Feel free to customize and expand upon this example based on the specific requirements of your application.
Remember to always validate file types and sizes in production applications to ensure security and prevent abuse of the file upload functionality.
Comments