Uploading Files - ASP.NET MVC2

Overview

This article walks through how to use the jQuery Multi-File Upload component with ASP.NET MVC2.

Installation

The JavaScript files (either jquery.MultiFile.js or jquery.MultiFile.pack.js) can be downloaded here.

ASPX Code


{copytext|aspx}
<% using (Html.BeginForm("Maintain", "Claim", 
        FormMethod.Post, new { enctype="multipart/form-data" }))
   {%>

. . .

<b>Select Documents and Images to Upload</b>
<br />
<input type="file" name="uxFileUpload" class="multi" accept="gif|jpg|pdf|png" />
<ul class="reminder">
<li>Files selected for upload will be listed above.</li>
<li>Click the "X" before any file to remove it from the list.</li>
<li>Files will be uploaded when you click the [Save Changes and Upload Attachments] button below.</li>
</ul>

. . .

<input type="submit" value="Save Changes and Upload Attachments" />

<% } %>

Controller Code

[HttpPost]
public ActionResult Maintain(int id, ClaimViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        //Upload files
        string path = "~/upload/attachments/" + id.ToString();
        List<string> files = HttpContext.Request.UploadFiles(path);

        //TODO: Save other data to the database
    }
    return View(viewModel);
}

Extension Method

Place the following code in a static class that's available (via using directives) to your controller code.

/// <summary>
/// Uploads all the files in the Request object to the path specified
/// </summary>
/// <param name="request">Typically HttpContext.Request</param>
/// <param name="virtualTargetPath">The path to upload the files to; e.g.,
/// "~/upload"</param>
/// <returns>A list of the file names uploaded</returns>
public static List<string> UploadFiles(this HttpRequestBase request, string virtualTargetPath)
{
    List<string> result = new List<string>();
    int imax = request.Files.Count - 1;
    string physicalTargetPath = HttpContext.Current.Server.MapPath(virtualTargetPath);

    for (int i = 0; i <= imax; i++)
    {
        HttpPostedFileBase file = request.Files[i];
        if (!Directory.Exists(physicalTargetPath))
            Directory.CreateDirectory(physicalTargetPath);
        string saveAsFileName = Path.Combine(physicalTargetPath, Path.GetFileName(file.FileName));
        file.SaveAs(saveAsFileName);
        result.Add(file.FileName);
    }
    return result;
}