0

I'm wondering if it would be possible at all to upload a file by posting it to a controller action in ASP.NET MVC. The dialog for this upload form will be dynamically generated and will be inside a jQuery dialog in my case.

I'm aware of the file input element but I'm not sure how to send the file to a controller action, not sure how to set the action parameter

Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58
Rafael
  • 1,099
  • 5
  • 23
  • 47
  • check this blog: https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/ . It explains it nicely. – Zippy Jun 26 '15 at 10:57
  • Yuu have not give enough detail of what your doing - but [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) may help –  Jun 26 '15 at 10:57
  • possible duplicate of [How can I upload files asynchronously?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – Rohit Arora Jun 26 '15 at 11:05

2 Answers2

1

Your action should like this:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");
}

Taken from :http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

Then using jQuery Dialog for file upload:

$dialog.dialog("option", "buttons", {
    "Save": function () {
        var dlg = $(this);
        var formData = new FormData($("#" + formName)[0]);
        $.ajax({
            url: /Controller/upload,
            type: 'POST',
            data: formData,
            processData: false, 
            contentType: false,
            success: function (response, textStatus, xhr) {
            ...
                }
            },
            error: function (xhr, status, error) {
                ....
            }
        });
    },
    "Cancel": function () {
        $(this).dialog("close");
        $(this).empty();
    }

});
Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58
0
<form id="frmFile" method="post" enctype="multipart/form-data" action="<%=Url.Content("~/WriteSomeServerAction/")%>" >

</form>

//Put this form in modal

and Make Submit event will send file to Action.There you can access file as in Model element as like UploadedFileData .

if (_File.UploadedFileData != null && _File.UploadedFileData.ContentLength > 0)
                {
                    byte[] buffer = new byte[_File.UploadedFileData.ContentLength];
                    _File.UploadedFileData.InputStream.Read(buffer, 0, buffer.Length);
                    _File.FileData = System.Text.Encoding.Default.GetString(buffer);
                    _File.UploadedFileData = null;
                }
Parth Trivedi
  • 3,802
  • 1
  • 20
  • 40