Monday, 16 June 2014

File Upload in MVC 4

Go to>> Models>>Add>>Class >>Give the name 'Leedhar_UploadFile.cs' 

Add following codes 

using System;
using System.Collections.Generic;
using System.Linq
using System.Web;
using System.Data.Entity;
namespace UploadFile.Models
{
       public class Leedhar_UploadFile : DbContext
       {
             public DbSet  Upload {get;set;}
       }

}





For Creating Fields for the table 'Upload' 

Go to>> Models>>Add>>Class >>Give database name 'upload.cs' 

Add following codes 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace UploadFile.Models
{
    public class Upload
    {
        [Key]
        public virtual int Upload_id { get; set; }
        [Required]
        public virtual string Title { get; set; }

    }
}





Step 3:Creating View Page 

Go to>> 'AdminController.cs' right click on index>> Add view>>give name as 'UploadFile.cshtml' give the master page . Click Add button 



Add following codes to 'UploadFile.cshtml' 



Step 4:For saving the uploaded file to a folder we have to create a folder 'documents' within that create a sub folder 'Files' 

Step 5:Add following codes to the Admin Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UploadFile.Models;
using System.Data.Linq;
namespace UploadFile.Controllers
{
   
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        Leedhar_UploadFile _DB = new Leedhar_UploadFile();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UploadFile()
        {
            ViewData["Success"] = "";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile(string Title)
        {
              _DB.Upload.Add(new Upload() { Title = Title });
              _DB.SaveChanges();
           
               int Id = (from a in _DB.Upload

                select a.Upload_id).Max();

            if (Id > 0)
            {
                if (Request.Files["file"].ContentLength > 0)
                {
                    string extension = System.IO.Path.GetExtension(Request.Files["file"].FileName);
                    string path1 = string.Format("{0}/{1}{2}", Server.MapPath("~/documents/Files"), Id, extension);
                    if (System.IO.File.Exists(path1))
                     System.IO.File.Delete(path1);

                    Request.Files["file"].SaveAs(path1);

                }
                ViewData["Success"] = "Success";
            }
            else
            {
                ViewData["Success"] = "Upload Failed";
            }
            return View();
        }


    }
}




Step 6:Debug 



The database will be created when we click the submit button 


br>The file is stored in the folder 'Files' 



No comments:

Post a Comment