【问题标题】:Passing in HttpPostedFileBase and FormCollection from Ajax从 Ajax 传入 HttpPostedFileBase 和 FormCollection
【发布时间】:2017-08-03 12:20:58
【问题描述】:

我目前正在开展一个项目,其中以前的承包商在我们的站点内有一个附件区域。这件作品大部分工作,但在上传文件后重定向回来时出现问题,另外我不喜欢页面重新加载整个页面只是为了更新网格以显示上传的文件。

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

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

下面是我的代码。

查看(上传.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 对象的提示。

注意 长话短说,你不能这样做。我不得不努力学习,但从未找到解决方案。我确实找到了一种方法来下载,但不是上传。

【问题讨论】:

  • 不清楚你在这里问什么。首先,您不能使用您显示的代码上传文件(使用data: $('form').serialize(),),并且文件在POST 方法中将始终为null。你需要使用FormData(参考this answer)。
  • 你是什么意思返回强制下载Json对象? (作为旁注,您的 @Html.ValidationMessage("file","File is required") 毫无意义 - 您在输入和返回的 json 中没有任何 data-val-* 属性,而不是视图,因此它永远不会被使用。

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


【解决方案1】:

选项:

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

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

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

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

【讨论】:

  • 以上都不能帮助消除下载问题...这只会改变您提交表单的方式。此外,返回 false 会完全停止页面...它会终止向控制器的提交...
  • 糟糕,我以为每次提交时页面都会刷新,让我继续努力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2014-07-08
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多