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<httppostedfilebase> files { get; set; }
public int Id { get; set; }
public string File { get; set; }
public string Type { get; set; }
}
}
</httppostedfilebase>
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> Filetables { get; set; }
}
}
</filetables>
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.
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.
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<filetables> ObjFiles = new List<filetables>();
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");
}
}
}
}
</filetables>
</filetables>
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<dynamicappendpartial.models.filetables>
@{
ViewBag.Title = "Index";
}<style type="text/css">
.btn {
width: 100px;
background: #00BCD4;
border: 1px solid;
border-color: white;
color: white;
}
.card {
width: 100%;
}
.gridborder {
margin: 20px;
border-top: 2px solid #DED8D8;
}
</style><div style="border: 1px solid #DED8D8; width: 900px; font-family: Arial;">
@using (@Html.BeginForm(null, null, FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
if (TempData["Message"] != null)
{<p style="font-family: Arial; font-size: 16px; font-weight: 200; color: red">@TempData["Message"]</p>
}
<div class="card mb-3"><div class="card-body"><h2 style="color: #47bfed">FILE UPLOAD AND DOWNLOAD IN ASP NET</h2>
<p class="card-text"><b style="color: #FF5722">File:</b></p>
<p class="card-text"> <input id="files" multiple="multiple" name="files" type="file"></p>
<input class="btn btn-primary" name="submit" type="submit"></div></div>
}
@foreach (var item in Model)
{
}
<table class="gridborder row-borderhover order-column dataTable no-footer"><tbody><tr><td> </td></tr></tbody><tbody><tr><td> </td><th class="sorting_asc">
@Html.DisplayNameFor(model => model.File)</th><td> </td><th class="sorting">
@Html.DisplayNameFor(model => model.Type)</th><td> </td><th class="sorting"> </th><td> </td></tr><tr><td> </td><td class="sorting_1">
@Html.DisplayFor(modelItem => item.File)</td><td> </td><td class="sorting_1">
@Html.DisplayFor(modelItem => item.Type)</td><td> </td><th class="sorting">
@Html.ActionLink("Download", "Download", new { fileName = item.File })</th><td> </td></tr></tbody></table></div>
</dynamicappendpartial.models.filetables>
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.
[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]
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.
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.
Top comments (0)