使用jQuery上传文件并将其发布到Controller [英] Upload file using jQuery and post it to Controller

查看:203
本文介绍了使用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();
    }

});

这篇关于使用jQuery上传文件并将其发布到Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆