Saturday, June 19, 2021

ASP.NET MVC Framework - Upload Multiple Files To Web Server

Create an ASP.NET MVC Framework 4.7.2 based application.
Design the view to upload the files as given below.

<form action="UploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="files" id="files" value="" multiple />
    <input type="submit" name="name" value="Upload Files" />
    @{
        HtmlString msg = new HtmlString(ViewBag.status);
    }
    <p>@msg</p>
</form>

Create FileController /UploadFile method with following code.

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace WebAppHttp.Controllers
{
    public class FileController : Controller
    {
        // GET: File
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase[] files)
        {
            string filenm = String.Empty;
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    
                    var filename = Guid.NewGuid().ToString() + Path.GetFileName(file.FileName);
                    var serverpath = Server.MapPath("~/UploadedFiles/");
                    var fullPath = Path.Combine(serverpath, filename);
                    file.SaveAs(fullPath);
                    filenm = filenm + "
"+ file.FileName; } } ViewBag.status = filenm; return View(); } } }

Note the following points.
  • Use HttpPostedFileBase parameter with HttpPost action method to upload single file.
  • Use HttpPostedFileBase[] array parameter with HttpPost action method to upload multiple files.
  • HtmlString class belongs to System.Web. It represents an HTML-encoded string that should not be encoded again.
OUTPUT:

UploadedFiles folder

No comments:

Post a Comment

Hot Topics