×

iFour Logo

How to Upload and return files in ASP.NET MVC?

Kapil Panchal - August 13, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
How to Upload and return files in ASP.NET MVC?

Table of Content

In this blog, we will shed light on how to upload and return a file in ASP.NET MVC.

When a user uploads files, they should be uploaded to their project folder. We need to create a folder for the uploaded file in our project. Let’s get started with creating an MVC application.

Creating MVC Application


Create a new MVC application for file uploading and downloading.

Adding Folder

Here, we created a folder in our project to store uploaded files.

Storing_Uploaded_File

[Fig :- Storing Uploaded File]

We need to create a model class for file upload and return files. Right-click on Model Folder and add a class file. Here I will use the code-first approach to implement File upload and return functionality. Place the following code inside the class file.

Filetables.cs
using System.Collections.Generic;
using System.Web;
namespace Dynamicappendpartial.Models
{
    public class Filetables
    {
        public IEnumerable files { get; set; }
        public int Id { get; set; }
        public string File { get; set; }
        public string Type { get; set; }
    }
}

					

Right-click on Models and add Ado.Net Entity Data model.

Empty_Code_First_model

[Fig :- Empty Code First model]

This Empty code First model creates a context file for your database connection. You can now add your Filetables class within the context file shown below.

using System;
using System.Data.Entity;
using System. Linq;
namespace Dynamicappendpartial.Models
{
    public class FileBlog: DbContext
    {
        public FileBlog(): base("name=FileBlog")
        {
        }
        public virtual DbSet Filetables { get; set; }
    }
}

				

Now, we need to execute all the required Migrations commands within the package manager control.

We need to add a controller. Right-click on the Controller folder and click on add > controller.

Creating_Controller

[Fig :- Creating Controller]

Select empty controller form list and give the suitable name of the controller. Here I give controller name as Filetables. And place the following code inside the controller.

Add Controller

[Fig :- Add Controller]


FiletableController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Dynamicappendpartial.Models;
namespace Dynamicappendpartial.Controllers
{
    public class FiletablesController : Controller
    {
        private FileBlog db = new FileBlog();
        // GET: Filetables
        public ActionResult Index()
        {
            List ObjFiles = new List();
            foreach (string strfile inDirectory.GetFiles(Server.MapPath("~/UploadFile")))
            {
                FileInfo fi = new FileInfo(strfile);
                Filetables obj = new Filetables();
                obj.File = fi.Name;
                obj.Type = GetFileTypeByExtension(fi.Extension);
                ObjFiles.Add(obj);
            }
            return View(ObjFiles);
        }
        public FileResult Download(string fileName)
        {
            string fullPath = Path.Combine(Server.MapPath("~/UploadFile"), fileName);
            byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
            return File(fullPath, "application/force-download", Path.GetFileName(fullPath));
        }
       
        private string GetFileTypeByExtension(string extension)
        {
            switch (extension.ToLower())
            {
                case ".docx":
                case ".doc":
                    return "Microsoft Word Document";
                case ".xlsx":
                case ".xls":
                    return "Microsoft Excel Document";
                case ".txt":
                    return "Text Document";
                case ".jpg":
                case ".png":
                    return "Image";
                default:
                    return "Unknown";
            }
        }
        [HttpPost]
        public ActionResult Index(Filetables doc)
        {
             try
               {
                foreach (var file in doc.files)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var filePath = Path.Combine(Server.MapPath("~/UploadFile"), fileName);
                        file.SaveAs(filePath);
                    }
                }
                TempData["Message"] = "files uploaded successfully";
                return RedirectToAction("Index");
            }
            catch
            {
                TempData["Message"] = "File upload Failed!!";
                return RedirectToAction("Index");
            }
      }
    }
}

				

Here I am creating two index methods one for uploading content to the database and one for uploading the file. The first index method is used to retrieve the uploaded file list and display it on the index page. On the same index page, I will create a form to upload files in the database.

The Last Index method in the controller is for uploading a file on a server. I want to store all files inside the upload file folder we created before starting the code. And use the TempData to display the message after files are uploaded successfully. If any exception occurs during execution or if the file was not uploaded successfully TempData shows File Uploaded Failed message on view.

In the controller, I am creating one method for file Extension. This method is used to display which type of file we uploaded to the database. And also create a method for downloading an uploaded file.

Right-click on the index method and add a view for the index method.


IndexView
@model IEnumerable
          
@{
    ViewBag.Title = "Index";
}
@using (@Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { if (TempData["Message"] != null) {

@TempData["Message"]

}

FILE UPLOAD AND DOWNLOAD IN ASP NET

File:

} @foreach (var item in Model) { }

Here in view I am creating an upload file and retrieve a list of the uploaded file in the same view you can modify the code as per your requirements.

For the Uploading file, we have to require an input type file so we can select the file.

Searching for Reliable ASP.NET Development Company ?

Now run the application. On index view, you can show the choose file option.

Index_view_for_File_Uploading

[Fig :- Index view for File Uploading]

If the file was upload successfully you can show the file upload successfully message in view.

Uploaded_file_Display_with_the_message

[Fig :- Uploaded file Display with the message]

If the file was not uploaded or we can click submit button without selecting the file it will display the File upload failed message in view.

Uploaded_file_with_the_failed_message

[Fig :- Uploaded file with the failed message]

 

Uploaded_file

[Fig :- Uploaded file]

You can see all the uploaded files inside the folder we have created.

Click on the Download link to download the file. Here I download all files you can show the downloaded file in the browser.

Download_File

[Fig :- Download File]

Conclusion


Here in this blog, I try to explain how to upload files in a database and how to retrieve the list of the file uploaded in a database, and how to download the uploaded file from the database with a successful and error message.

How to Upload and return files in ASP.NET MVC? Table of Content 1. Creating MVC Application 1.1Adding Folder 2. Conclusion In this blog, we will shed light on how to upload and return a file in ASP.NET MVC. When a user uploads files, they should be uploaded to their project folder. We need to create a folder for the uploaded file in our project. Let’s get started with creating an MVC application. Creating MVC Application Create a new MVC application for file uploading and downloading. Adding Folder Here, we created a folder in our project to store uploaded files. [Fig :- Storing Uploaded File] We need to create a model class for file upload and return files. Right-click on Model Folder and add a class file. Here I will use the code-first approach to implement File upload and return functionality. Place the following code inside the class file. Filetables.cs using System.Collections.Generic; using System.Web; namespace Dynamicappendpartial.Models { public class Filetables { public IEnumerable files { get; set; } public int Id { get; set; } public string File { get; set; } public string Type { get; set; } } } Right-click on Models and add Ado.Net Entity Data model. [Fig :- Empty Code First model] This Empty code First model creates a context file for your database connection. You can now add your Filetables class within the context file shown below. using System; using System.Data.Entity; using System. Linq; namespace Dynamicappendpartial.Models { public class FileBlog: DbContext { public FileBlog(): base("name=FileBlog") { } public virtual DbSet Filetables { get; set; } } } Now, we need to execute all the required Migrations commands within the package manager control. Read More: Generate Thumbnail Using Asp.net MVC We need to add a controller. Right-click on the Controller folder and click on add > controller. [Fig :- Creating Controller] Select empty controller form list and give the suitable name of the controller. Here I give controller name as Filetables. And place the following code inside the controller. [Fig :- Add Controller] FiletableController using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Dynamicappendpartial.Models; namespace Dynamicappendpartial.Controllers { public class FiletablesController : Controller { private FileBlog db = new FileBlog(); // GET: Filetables public ActionResult Index() { List ObjFiles = new List(); foreach (string strfile inDirectory.GetFiles(Server.MapPath("~/UploadFile"))) { FileInfo fi = new FileInfo(strfile); Filetables obj = new Filetables(); obj.File = fi.Name; obj.Type = GetFileTypeByExtension(fi.Extension); ObjFiles.Add(obj); } return View(ObjFiles); } public FileResult Download(string fileName) { string fullPath = Path.Combine(Server.MapPath("~/UploadFile"), fileName); byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath); return File(fullPath, "application/force-download", Path.GetFileName(fullPath)); } private string GetFileTypeByExtension(string extension) { switch (extension.ToLower()) { case ".docx": case ".doc": return "Microsoft Word Document"; case ".xlsx": case ".xls": return "Microsoft Excel Document"; case ".txt": return "Text Document"; case ".jpg": case ".png": return "Image"; default: return "Unknown"; } } [HttpPost] public ActionResult Index(Filetables doc) { try { foreach (var file in doc.files) { if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var filePath = Path.Combine(Server.MapPath("~/UploadFile"), fileName); file.SaveAs(filePath); } } TempData["Message"] = "files uploaded successfully"; return RedirectToAction("Index"); } catch { TempData["Message"] = "File upload Failed!!"; return RedirectToAction("Index"); } } } } Here I am creating two index methods one for uploading content to the database and one for uploading the file. The first index method is used to retrieve the uploaded file list and display it on the index page. On the same index page, I will create a form to upload files in the database. The Last Index method in the controller is for uploading a file on a server. I want to store all files inside the upload file folder we created before starting the code. And use the TempData to display the message after files are uploaded successfully. If any exception occurs during execution or if the file was not uploaded successfully TempData shows File Uploaded Failed message on view. In the controller, I am creating one method for file Extension. This method is used to display which type of file we uploaded to the database. And also create a method for downloading an uploaded file. Right-click on the index method and add a view for the index method. IndexView @model IEnumerable @{ ViewBag.Title = "Index"; }.btn { width: 100px; background: #00BCD4; border: 1px solid; border-color: white; color: white; } .card { width: 100%; } .gridborder { margin: 20px; border-top: 2px solid #DED8D8; } @using (@Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { if (TempData["Message"] != null) {@TempData["Message"] } FILE UPLOAD AND DOWNLOAD IN ASP NET File: } @foreach (var item in Model) { }    @Html.DisplayNameFor(model => model.File)  @Html.DisplayNameFor(model => model.Type)     @Html.DisplayFor(modelItem => item.File)  @Html.DisplayFor(modelItem => item.Type)  @Html.ActionLink("Download", "Download", new { fileName = item.File })  Here in view I am creating an upload file and retrieve a list of the uploaded file in the same view you can modify the code as per your requirements. For the Uploading file, we have to require an input type file so we can select the file. Searching for Reliable ASP.NET Development Company ? CONTACT US Now run the application. On index view, you can show the choose file option. [Fig :- Index view for File Uploading] If the file was upload successfully you can show the file upload successfully message in view. [Fig :- Uploaded file Display with the message] If the file was not uploaded or we can click submit button without selecting the file it will display the File upload failed message in view. [Fig :- Uploaded file with the failed message]   [Fig :- Uploaded file] You can see all the uploaded files inside the folder we have created. Click on the Download link to download the file. Here I download all files you can show the downloaded file in the browser. [Fig :- Download File] Conclusion Here in this blog, I try to explain how to upload files in a database and how to retrieve the list of the file uploaded in a database, and how to download the uploaded file from the database with a successful and error message.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

React 19 For Business: Latest Features and Updates
React 19 For Business: Latest Features and Updates

When I first started exploring React.js for our company’s project, I felt a bit lost. It was like trying to solve a big puzzle without all the pieces! But as I kept learning and trying them practically, I discovered some really cool features that blew my mind making everything seamlessly easier.

MySQL vs Azure SQL Database: Cost, Security, and Compatibility Considerations
MySQL vs Azure SQL Database: Cost, Security, and Compatibility Considerations

This blog is a continuation of MySQL vs Azure SQL Database – Part 1 , where we compared MySQL and Azure SQL databases. We learned how important it is to identify and evaluate client...

Is It Worth Using Azure With Power Platforms For Financial Business?
Is It Worth Using Azure With Power Platforms For Financial Business?

The era of traditional software development is fading; Azure Cloud and Power Platform services are taking charge to run businesses of the new age. When it comes to Financial business,...