How to upload a file in ASP.Net MVC 5.

We learn about that how to upload a file using file-uploader in MVC. In this article we are Form Method (It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.) And HtmlAttributes (This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files)

Note: We need to check that we have created a folder or not if then must be created.

We have created Fileuploader name Controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace MVCCODESOLUTIONS.Controllers
    public class FileuploaderController : Controller
        // GET: Fileuploader
        public ActionResult view()
            return View();

        public ActionResult View(HttpPostedFileBase postedFile)
            if (postedFile != null)
                string path = Server.MapPath("~/Uploads/");
                if (!Directory.Exists(path))

                postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));

                ViewBag.Message = "File uploaded successfully.";

            return View();

We have created View name Controller.
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    <title>File uploader example</title>
        @using (Html.BeginForm("View", "Fileuploader", FormMethod.Post, new { enctype = "multipart/form-data" }))
            <span>Select File:</span>
            <input type="file" name="postedFile" />
            <hr />
            <input type="submit" value="Upload" />
            <br />



How to upload a file in ASP.Net MVC 5. How to upload a file in ASP.Net MVC 5. Reviewed by NEERAJ SRIVASTAVA on 12:19:00 PM Rating: 5

No comments:

Powered by Blogger.