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.

Controller:-
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
        [HttpGet]
        public ActionResult view()
        {
            return View();

        }
        [HttpPost]
        public ActionResult View(HttpPostedFileBase postedFile)
        {
            if (postedFile != null)
            {
                string path = Server.MapPath("~/Uploads/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

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

                ViewBag.Message = "File uploaded successfully.";
               
            }

            return View();
        }

    }
}
View:
We have created View name Controller.
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>File uploader example</title>
</head>
<body>
    <div>
        @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 />
            @ViewBag.Message
        }
    </div>
</body>

</html>

OUT-PUT:-


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.