Friday, 25 April 2014

MVC

How to FileUpload in MVC 3 ?

1. Add Home Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication10.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index(IEnumerable<HttpPostedFileBase> File)
        {
            string physicalpath = HttpContext.Server.MapPath("~") + "UploadImages" + "\\";
            for (int i = 0; i < Request.Files.Count; i++)
            {
                Request.Files[0].SaveAs(physicalpath + System.IO.Path.GetFileName(Request.Files[i].FileName));
            }
            return View();
        }

    }
}

2. Create Index view

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <fieldset>
    <legend>
    Upload Files
    </legend>
    <ol>
    <li><input type="file" id="fileUPload1" name="fileUpload1" /></li>
    </ol>
        <input type="submit" value="Upload" />
    </fieldset>
}


Its look alike:-----
3. Browse File and Upload it.

No comments:

Post a Comment

Thanks for comments.