Uploading files in ASP.Net MVC

asplogo-square

 

Uploading files in a web application is a common task that every web developer has done at least a couple of times but implementing this task in ASP.Net MVC is kind of different than other web frameworks.
In this article, we’re going to see how we can upload files to the server in ASP.net MVC framework and you’ll see how much easier this is can be done because almost all the nasty work is already done for us.

Single file upload

First of all we need a HTTP GET action that will render the upload file Form. The view will be very simple, something like this:

<h2>Upload File</h2>
@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label for="fileToUpload">Your file to upload</label>
    <input id="fileToUpload" name="fileToUpload" type="file" value="" />
    <br />
    <input name="submit" type="submit" value="upload" />

}

as you can see the client side code is very simple to write:

  • A simple HTML form with enctype=”multipart/form-data” attribute
  • A HTML file input
  • A submit button

Now let’s move on to the server side code.
In our controller let’s add an HTTP POST action method that will handle the posted data and save it to the file system then return some informations about the posted file. The action method will looks like this:

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase fileToUpload)
        {
            if (fileToUpload != null)
            {
                fileToUpload.SaveAs(Server.MapPath("~/uploads/") + fileToUpload.FileName);
                ViewBag.Message = "Your file was uploaded successfully.";
                ViewBag.FileName = fileToUpload.FileName;
                ViewBag.ContentLength = fileToUpload.ContentLength;
                ViewBag.ContentType = fileToUpload.ContentType;
            }
            return View();
        }

let’s also update our view to show the posted file details

<h2>Upload File</h2>
@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <div style="background-color: bisque;">
        <span style="font-weight: bold;">Status: </span>@ViewBag.Message<br />
        <span style="font-weight: bold;">FileName: </span>@ViewBag.FileName<br />
        <span style="font-weight: bold;">ContentLength: </span>@ViewBag.ContentLength<br />
        <span style="font-weight: bold;">ContentType: </span>@ViewBag.ContentType
    </div>
}

@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label for="fileToUpload">Your file to upload</label>
    <input id="fileToUpload" name="fileToUpload" type="file" value="" />
    <br />
    <input name="submit" type="submit" value="upload" />

}

Multiple file upload

If we want to upload multiple file to the server, we’ve to add a new html file input for each file in the client HTML form. Of course the HTML form must be always with the enctype=”multipart/form-data” attribute

<h2>Multiple File Upload</h2>
@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <div style="background-color: bisque;">
        <span style="font-weight: bold;">Status: </span>@ViewBag.Message
    </div>
}

<form action="@Url.Action("Index", "Upload")" enctype="multipart/form-data" method="POST">
    <label>Your files to upload</label>

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="filesToUpload" type="file" value="" /><br />

    <input name="submit" type="submit" value="upload" />
</form>

In order to successfully upload all the selected files, the action method on the server side must accept a List<HttpPostedFileBase> object, then we’ve to iterate through each file and save it to the file system

        [HttpPost]
        public ActionResult Index(List<HttpPostedFileBase> filesToUpload)
        {
            if (filesToUpload != null)
            {
                foreach (var file in filesToUpload.Where(file => file != null))
                {
                    file.SaveAs(Server.MapPath("~/uploads/") + file.FileName);
                }
                ViewBag.Message = string.Format("You upload {0} files.", filesToUpload.Count(f => f != null));
            }
            return View();
        }

Summary

As you can see uploading single or multiple file using ASP.net MVC is very easy and simple to implement because almost all the dirty work is already done for us.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s