从Ajax传入HttpPostedFileBase和FormCollection

时间:2017-03-13 13:04:55

标签: c# json ajax asp.net-mvc-5 httppostedfilebase

我目前正在开展一个项目,前一个承包商在我们的网站内有一个附件区域。这个部分大部分都有用,但在上传文件后重定向时会出现问题,而且我不喜欢页面只是为了更新网格来显示上传的文件而重新加载页面。

我的目标是为上传和表单提交执行Ajax调用。我添加了这个,但是,返回强制下载Json对象(使用IE 11)。我已经研究过如何解决这个问题,并且还没有找到任何实质性的方法。

是否可以使用Ajax上传文件而不发回Json对象的下载?

以下是我的代码。

查看(Upload.cshtml)

@using (Html.BeginForm("Upload", "PM", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmUpload" }))
{
   @Html.ValidationSummary(true)
   <table>
      ...
      <tr>
          <td>@Html.Label("File: ")</td>
          <td>
            <input type="file" name="file" id="file"/>
            @Html.ValidationMessage("file","File is required")
          </td>
      </tr>
      ...

      <tr>
          <td colspan="2">
            <p>
                <button type="submit" class="t-button" id="btnSubmit">
                    Attach</button>
                <button type="button" class="t-button" onclick="CloseAttachmentWindow()">
                    Cancel</button>
            </p>
        </td>
      </tr>
  </table>    
}

<script type="text/javascript">
  $(document).ready(function () {        
    $("#btnSubmit").click(function (e) {
        e.preventDefault();

        if (!$('form').valid())
            return false;

        //Upload document
        $.ajax({
            type: "POST",
            cache: false,
            url: "/PM/Upload",
            dataType: "json",
            contentType: false,
            processData: false,
            data: $('form').serialize(),
            success: function (result) {
                if (result.success) {
                    var window = $("#error").data("tWindow");
                    window.content("<b>Attachment successfully added</b>").title("Success!");
                    window.center().open();

                    CloseAttachmentWindow();
                }
                else {
                    var window = $("#error").data("tWindow");
                    window.content("<b>Error: Unable to Upload Document.  Please try again.  "
                                        + "If this fails, contact the administrators with the below details.</b>"
                                        + '\n' + '\n' + result.Error).title("Error");
                    window.center().open();
                }
            },
            error: function (xhtr, e, e2) {
                var window = $("#error").data("tWindow");
                window.content(e + '\n' + xhtr.responseText, 'error', '');
                window.center().open();
            }
        });
    });
  });
</script>

PMController.cs

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, FormCollection formcollection)
{
        if (file != null)
        {
            var cntPOC = int.Parse(Session["cntPOC"].ToString());
            try
            {
                var cntFileType = _fileTypeRepo.GetCntFileTypeByMimeType(file.ContentType);
                if (cntFileType == 0)
                    throw new Exception("This file type is not supported");

                var strAttachmentName = formcollection["AttachmentName"];
                var strAttachmentType = formcollection["AttachmentType"];

                var length = file.ContentLength;
                var tmpFile = new byte[length];

                if (tmpFile.Count() > 0)
                {
                    file.InputStream.Read(tmpFile, 0, length);
                    var intAttchmentId = _AttachRepo.GetNextAttachmentId() + 1;

                    var objAttachment = new TBLATTACHMENT
                    {
                        CNTATTACHMENT = intAttchmentId,
                        CNTPOC = cntPOC,
                        CNTFILETYPE = cntFileType,
                        CNTATTACHMENTTYPE = Convert.ToDecimal(strAttachmentType),
                        DTMCREATED = DateTime.Now,
                        STRATTACHMENTTITLE = strAttachmentName,
                        BLBATTACHMENT = tmpFile,
                        STRORIGINALFILENAME = file.FileName,
                        YSNDELETED = 0
                    };

                    _AttachRepo.Add(objAttachment);
                    _AttachRepo.Save();

                    return Json(new { success = true, Error = "" });
                }
                //File not real
                else
                    return Json(new { success = false, Error = "Please select appropriate file" });
            }
            catch (Exception ex)
            {
                logger.LogError("File Upload", ex);

                if (ex.InnerException != null)
                    ModelState.AddModelError("Error", ex.InnerException.ToString());
                else
                    ModelState.AddModelError("Error", ex.Message.ToString());

                TempData["ModelState"] = ModelState;

                return Json(new { success = false, Error = ex.Message });
            }
        }
        else
        {
            logger.LogError("File Upload Error. File was not selected");
            ModelState.AddModelError("Error", "Please select file");
            TempData["ModelState"] = ModelState;

            return Json(new { success = false, Error = "File was not selected" });
        }
}

按原样,使用此代码,我可以上传文档,但是,我会在返回时收到下载Json对象的提示。

1 个答案:

答案 0 :(得分:-1)

选项:

  • 删除更改按钮类型提交到按钮<input type="button"/>
  • <input type="submit" onclick="return false">
  • return false;或添加事件处理程序

    $("input[type='submit']").click(function() { return false; }); 要么 $("form").submit(function() { return false; });

  • <form onsubmit="return false"> ...</form> 为了避免刷新所有“按钮”,即使分配了onclick。

将提交类型更改为按钮是最佳选择。