HTTP Posted File Helper V.1.0.2 Nugget Link
This is a light weight library that helps in the posting of files to IIS Web Server by providing a helper class FileHElper.cs which contains overloaded method ProcessFile() and ProcessFIleAsync() that reduces the boilerplate in posting files.
Installing..
Type the command below in Visual Studio Nuget Package Manager Console to install the library.
- PM> Install-Package HttpPostedFileHelper
Usage
Processing Single Files (Basic Usage)
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult UploadFile(HttpPostedFileBase file) {
-
- FileHelper filehelper = new FileHelper();
- filehelper.ProcessFile(file, "/MyTargetLocation");
- return view();
- }
Processing Multiple Files
This makes a provision for multiple files being uploaded to the Server with an overridden method for processing an IEnumerable of files (HttpPostedFileBase Collection).
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {
- FileHelper filehelper = new FileHelper();
-
- int postedfiles = filehelper.ProcessFile(file, "/MyTargetLocation");
- if (postedfiles > 0) {
-
- }
- return View("Home");
- }
Asynchronous File Processing
Processing files can be done asynchronously. This allows large files to be processed in the background thread freeing the main thread.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task < ActionResult > UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {
- FileHelper filehelper = new FileHelper();
- await filehelper.ProcessFileAsync(file, "/MyTargetLocation");
-
- return View("Home");
- }
Reject File Extensions During Upload
You can specify the file types to be rejected during an upload by supplying a string of the file extensions.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task < ActionResult > UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {
- FileHelper filehelper = new FileHelper();
- string reject = ".jpeg,.png,.svg";
- int postedfiles = await filehelper.ProcessFileAsync(file, "/MyTargetLocation", reject);
- if (postedfiles > 0) {
-
- }
- return View("Home");
- }
Thanks for reading this blog. I hope it will help someone.