Search code examples
c#asp.net-mvc-3file-uploadopenfiledialog

Uploading file in with ASP.NET MVC3 (OpenFileDialog alternative)


I'm trying to replicate some webforms functionality that uploads a csv file in an MVC3 project and am coming unstuck. I have the following requirements:

(Short version is that I need something similar to the Filter, InitialDirectory and preferably but not necessarily, the MultiSelect properties of the System.Windows.Controls.OpenFileDialog class for MVC3)

  1. Single button displayed that opens the open file dialog
  2. Upload begins when open is clicked in the dialog
  3. The file type in the dialog should be restricted to csv, txt and All files
  4. The initial directory should be able to be set depending on user preferences

I've used jQuery for the first two requirements (shown below) but am not if this is the best way or how to accomplish the last two.

View:

@using (Html.BeginForm("Import", "Date", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUpload" }))
{
    <input type="file" name="file" id="file" style="display: none;" />
    <input type="button" id="import" value="Import" />
}

<script type="text/javascript">
    $(document).ready(function () {

        $('#file').change(function () {
            $('#fileUpload').submit();
        });

        $('#import').click(function () {
            $('#file').trigger('click');
        });

    });
</script>

Controller:

[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
      // do stuff
}

Any ideas?


Solution

  • It's not possible to do unless you use a Flash or Silverlight plugin. I use Uploadify and it should do everything you need.