使用jQuery上传文件并将其发布到Controller

使用jQuery上传文件并将其发布到Controller

问题描述:

我想知道是否可以通过将文件发布到ASP.NET MVC中的控制器操作来上传文件.在我的情况下,此上传表单的对话框将动态生成,并位于jQuery对话框中.

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.

我知道文件输入元素,但不确定如何将文件发送到控制器操作,不确定如何设置action参数

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

您的操作应为:

[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");
}

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

然后使用jQuery对话框上传文件:

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

});