尝试POST图像文件 - ActionResult中的参数为null

时间:2014-11-18 11:50:29

标签: jquery asp.net-mvc-5 image-uploading

我想用MVC和jQuery做一个文件上传,但是我的paremter是null。在我的jQuery中,我获取表单数据并为其分配变量,然后将其POST到ActionResult。我的参数为null,我不确定我是否正确传递数据。

HTML

<table>
                <tr>
                    <td><img src="@Url.Content("~/AMTImages/UserAvatar.png")" width="64" height="64" style="border: thin solid" /></td>
                    <td></td>
                    <td></td>
                    <td>
                        <form enctype="multipart/form-data" id="imageUploadForm">
                            <table>
                                <tr>
                                    <td>@Html.LabelFor(m => m.DisplayName, "Display Name: ")</td>
                                    <td style="padding-left: 10px;">@Html.TextBoxFor(m => m.DisplayName)</td>
                                </tr>
                                <tr>
                                    <td>@Html.LabelFor(m => m.UserImage, "User Image: ")</td>
                                    <td style="padding-left: 10px; float: right;">@Html.TextBoxFor(m => m.UserImage, new { type = "file", accept = "image/*" })</td>
                                </tr>
                            </table>
                        </form>
                    </td>
                    <td>
                        <table style="display:none;">
                            <tr>
                                <td>
                                    <progress></progress>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>

的JavaScript

$(':file').change(function () {
    var file = this.files[0];

    $.ajax({
        url: '@Url.Action("UploadImage", "User")',  //Server script to process data
        type: 'POST',
        data: file,
        beforeSend: function() {  
        },
        success: function () {
        },
        error: function () {
        },
        processData: false,
        contentType: file.type
    });
});

的ActionResult

 public ActionResult UploadImage(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }

            return View();
        }

1 个答案:

答案 0 :(得分:0)

您的UploadImage需要一个文件POST参数。你在哪里指定前端代码?看不到你传递的地方。

尝试将HttpPostedFileBase文件更改为HttpPostedFileBase userImage