Upload and Remove the file in Asp Dotnet Mvc





> How to upload file using path from database (.Jpg, ,xls, .txt, .docx and etc )

CREATE TABLE [dbo].[UploadFile]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY,
    [Category] int NOT NULL,
    [FileType] VARCHAR(50) NOT NULL,
    [Path]  VARCHAR(Max) NOT NULL,
    [Status] BIT NULL
)
execute the query......

>Open visualstudio and Create new project and name it UploadFile


1>Create a Model name UploadFileModel.-->and Map with Table and table name

[Table("UploadFile")]
public class UploadFileModel
{
   public in Id {get;set;}
   public int Category {get;set;}
   public string FileType {get;set;}
   public string Path {get;set;}
   public bool Status {get;set;}
}

Ctrl+ S  for save.


2> Create DefaultConnection Name class as given in web.config file of ConnectionString .
     Now  derive the DbContext
and mapp with DbSet with Model

Look over here:-

public class DefaultConnection : DbContext
{
public DbSet<UploadFileModel > uploadfilemodel { get;set;}
}

and 
Ctrl+S for save.



> Create Controller for Create ,Edit and Delete

using ItsMe.Areas.Admin.Models;
using ItsMe.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ItsMe.Areas.Admin.Controllers
{
    public class UploadFileController : Controller
    {
        DefaultConnection def = new DefaultConnection();
        public ActionResult Index()
        {
            var model = def.uploadfileContext.ToList();
            foreach (var i in model)
            {
                var aa= def.typeContext.Find(i.TypeId);
                var bb = def.categoryContext.Find(i.CategoryId);
                ViewBag.type = aa != null ? aa.Name : "Unknown Name";
                ViewBag.category = bb != null ? bb.Name : "Unknown Name";
            }
         
            return View(model);
        }

        public void DropdownList(UploadFile model)
        {
            var category = def.categoryContext.Where(r => r.Status == true).ToList();
            var type = def.typeContext.Where(r => r.Status == true).ToList();

            IList<SelectListItem> AvailableCategory = new List<SelectListItem>();
            IList<SelectListItem> AvailableType = new List<SelectListItem>();

            foreach (var i in category)
            AvailableCategory.Add(new SelectListItem { Text = i.Name, Value= i.Id.ToString() });
            SelectList ddlcategory = new SelectList(AvailableCategory,"Text","Value");

            foreach (var i in type)
            AvailableType.Add(new SelectListItem { Text = i.Name, Value = i.Id.ToString() });
            SelectList ddltype = new SelectList(AvailableType, "Text", "Value");

            ViewBag.AvailableCategory = ddlcategory;
            ViewBag.AvailableType = ddltype;
        }




        public ActionResult Create()
        {
            var model = new UploadFile();
            DropdownList(model);
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(UploadFile model , HttpPostedFileBase file)
        {
            DropdownList(model);
            if (ModelState.IsValid)
            {
                if (file!=null)
                {
                    var filename = Path.GetFileName(file.FileName);
                    var extension = Path.GetExtension(file.FileName);
                    var path = Server.MapPath("~/Content/UploadFile/"+filename+Guid.NewGuid().ToString().ToString().Substring(0, 6)+""+extension);
                    file.SaveAs(path);
                    model.Path = "~/Content/UploadFile/"+ Guid.NewGuid()+ extension;
                }
                else
                {
                    model.Path = "~/Content/UploadFile/empty.file";
                }
                                 
                def.uploadfileContext.Add(model);
                def.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(model);
        }
     
    }
}


Edit


public ActionResult Edit(int Id)
        {
            return View(def.uploadfileContext.Find(Id));
        }

        [HttpPost]
        public ActionResult Edit(UploadFile model, HttpPostedFileBase file)
        {
            try
            {              
           
                if (ModelState.IsValid)
                {
                    if (file != null)
                    {                    
                        FileInfo image = new FileInfo(HttpContext.Server.MapPath(model.Path));
                        if (image.Exists)//check file exsit or not
                        {
                            image.Delete();
                        }                    
                         var filename = Path.GetFileName(file.FileName);
                    var extension = Path.GetExtension(file.FileName);
                    var path = Server.MapPath("~/Content/UploadFile/"+filename+Guid.NewGuid().ToString().ToString().Substring(0, 6)+""+extension);
                    file.SaveAs(path);
                    model.Path = "~/Content/UploadFile/"+ Guid.NewGuid()+ extension;
                    }
                    else
                    {
                        model.Image = model.Path;
                    }
                    def.Entry(model).State = EntityState.Modified;
                    def.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(model);
            }
            catch (Exception ex)
            {
                ViewBag.Result = ex.Message;
                return View(model);
            }
        }

Delete

        [ActionName("Delete")]
        [HttpPost]
        public ActionResult Delete(int Id)
        {
            try
            {
                var fileupload=def.uploadfileContext.Find(Id);
                def.uploadfileContext.Remove(fileupload);
                def.SaveChanges();
                FileInfo image = new FileInfo(Server.MapPath(fileupload.Path));
                if (image.Exists)//check file exsit or not
                {
                    image.Delete();
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", new { smsg = ex.Message });
            }


        }




View Page of Index an Create

Index page

@model IEnumerable<ItsMe.Areas.Admin.Models.UploadFile>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CategoryId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.TypeId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Path)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Status)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @ViewBag.category
        </td>
        <td>
            @ViewBag.type
        </td>
        <td>
           <img src="@Url.Content(item.Path)" target="@Url.Content(item.Path)" style="width:20px; height:20px" />
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Status)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>



Create Page

@model ItsMe.Areas.Admin.Models.UploadFile

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm("Create","UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>UploadFile</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CategoryId,new SelectList(ViewBag.AvailableCategory, "Text","Value"), new {@class = "form-control"  })
                @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TypeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.TypeId,new SelectList(ViewBag.AvailableType,"Text","Value"), new {  @class = "form-control"  })
                @Html.ValidationMessageFor(model => model.TypeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
           <div class="col-md-2">  Upload File</div>
            <div class="col-md-8">
              <input type="file" name="file" id="file" />              
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Status)
                    @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


Edit Page



@model ItsMe.Areas.Admin.Models.UploadFile

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
@Html,HiddenFor(r=>r.Id)
}

<h2>Create</h2>

@using (Html.BeginForm("Create","UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>UploadFile</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CategoryId,new SelectList(ViewBag.AvailableCategory, "Text","Value"), new {@class = "form-control"  })
                @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TypeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.TypeId,new SelectList(ViewBag.AvailableType,"Text","Value"), new {  @class = "form-control"  })
                @Html.ValidationMessageFor(model => model.TypeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
           <div class="col-md-2">  Upload File</div>
            <div class="col-md-8">
              <input type="file" name="file" id="file" />              
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Status)
                    @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Edit" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>







Delete

@model ItsMe.Areas.Admin.Models.UploadFile

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
@Html,HiddenFor(r=>r.Id)
}

<h2>Create</h2>

@using (Html.BeginForm("Create","UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
 
    <div class="form-horizontal">
        <h4>UploadFile</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CategoryId,new SelectList(ViewBag.AvailableCategory, "Text","Value"), new {@class = "form-control"  })
                @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TypeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.TypeId,new SelectList(ViewBag.AvailableType,"Text","Value"), new {  @class = "form-control"  })
                @Html.ValidationMessageFor(model => model.TypeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
           <div class="col-md-2">  Upload File</div>
            <div class="col-md-8">
              <input type="file" name="file" id="file" />            
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Status)
                    @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Delete" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>








Create Folder (UploadFile in Content Folder) 

> To save the path of upload folder in Database .





 




Share this

Previous
Next Post »