how to upload a file in mvc



Step1:- Create a New Project in Visual Studio from File menu bar or Prss Ctrl+Shift+N

and Give a name it FileUpload. After Creating project create a folder with name 'UploadedFiles' in your project file.










Step 2:- Add a Empty Controller to your Project .




Step 3:- Click on Index method and Create a view with Name UploadFile.






Step 4:- Copy the following code in your created controller class.

 
FileUploadingController.cs

using System.IO;

using System.Web;

using System.Web.Mvc;

 

namespace FileUpload.Controllers

{

    public class FileUploadingController : Controller

    {

        // GET: FileUploading

 

        public ActionResult UploadFile()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult UploadFile(HttpPostedFileBase file)

        {

            try

            {

                if (file.ContentLength > 0)

                {

                    string fileName = Path.GetFileName(file.FileName);

                    string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);

                    file.SaveAs(path);

                }

                ViewBag.Message = "File Uploaded Successfully!!";

                return View();

            }

            catch

            {

                ViewBag.Message = "File upload failed!!";

                return View();

            }           

        }

    }

}




Step5:- Copy the following code in your created empty view.

 UploadFile.cshtml

@{

    ViewBag.Title = "UploadFile";

}

<h2>UploadFile</h2> 

@using (Html.BeginForm("UploadFile", "FileUploading", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

    <div>

        @Html.TextBox("file", "", new { type = "file" }) <br />

        <input type="submit" value="Upload" />

        @ViewBag.Message

    </div>

}


Note:- enctype is used for sending multipart/form-data(image ,video file etc) to server. 




Step 6:- Now Run your project and Upload  a file and check uploading file in your project folder "UploadedFiles".






   
 So now you successfully uploaded a file.

No comments:

Post a Comment