Step1: Add code in the view
@using (Html.BeginForm("Create", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<td style="border:none">
<div class="form-group">
@Html.LabelFor(model => model.files, "Attach File", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
@Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
</div>
</div>
</td>
Step2: Add Code in the model class
using System.Web;
public HttpPostedFileBase[] files { get; set; }
Step3: Add Code in the controller/service class
public ActionResult Create([Bind(Include = "Id,RequestId,ClaimCategory,ClaimDate,Currency,Amount,CreatedBy,FilePath,Status,ProfitCentre,NOTID,Employee,Comments,ProjectCode,Project")] ClaimCreation claimCreation, HttpPostedFileBase[] files, String hval)
{
if (Session["UserID"] == null)
{
return RedirectToAction("Login", "Account");
}
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
//Checking file is available to save.
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
//Save file to server folder
file.SaveAs(ServerSavePath);
FileDetail fd = new FileDetail();
fd.RequestId = claimCreation.RequestId;
fd.FileName = InputFileName;
fd.FilePath = ServerSavePath;
db.FileDetails.Add(fd);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
}
Note: FD is file details table where file name and information will be saved.
Step 4: Show saved file
<div class="panel panel-default">
@foreach (var fd in db.FileDetails.Where(f => f.RequestId == Model.RequestId))
{
<div class="row">
<div class="col-md-6">
<a href="@Url.Action("Download", "Controller", new { id = @fd.Id })">
<span class="glyphicon glyphicon-download-alt"></span> @fd.FileName
</a>
</div>
</div>
}
</div>
Step 5: Add code in the controller/service class
public FileResult Download(int id)
{
FileDetail fd = db.FileDetails.Find(id);
byte[] fileBytes = System.IO.File.ReadAllBytes(fd.FilePath);
string fileName = fd.FileName;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}