Upload file using jQuery and post it to Controller

2019-08-24 13:45发布

问题:

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

回答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();
    }

});


回答2:

<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;
                }