2017-03-13 1 views
0

저는 이전 계약자가 우리 사이트 내의 첨부 영역이있는 프로젝트에서 작업하고 있습니다. 이 부분은 대부분 작동하지만 파일을 업로드 한 후 다시 리디렉션 할 때 문제가 발생합니다. 또한 업로드 된 파일을 표시하기 위해 그리드를 업데이트하기 위해 페이지가 전체 페이지를 다시로드한다는 사실을 좋아하지 않습니다.Ajax에서 HttpPostedFileBase 및 FormCollection 전달하기

제 목표는 업로드 대 양식 제출 대신 Ajax 호출을하는 것입니다. 나는 이것을 추가했다. 그러나 반환은 IE 11을 사용하여 Json 객체를 강제로 다운로드한다. 이 문제를 해결하는 방법을 연구했으며 아직 해결 방법이 부족합니다.

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 개체를 다운로드 프롬프트 수 돌아올 때.

+0

여기에 묻는 것이 명확하지 않습니다. 첫째로,'data : $ ('form'). serialize(),'를 사용하여 보여준 코드로 파일을 업로드 할 수 없으며 파일은 POST 메소드에서 항상 'null'이됩니다. 당신은'FormData'를 사용해야합니다 ([이 답변을 참조하십시오 (http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it- in-mvc/29293681 # 29293681)). –

+0

그리고 반환은 Json 객체의 다운로드를 강제합니까? (그리고 부수적으로, 당신의'@Html.ValidationMessage ("file", "File is required")'는 무의미하다 - input과 return json에는'data-val- *'속성이 없다. 보기가 사용되지 않을 것입니다 .. –

답변

-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이 할당 된 경우에도 모든 "버튼"에서 새로 고침을 방지합니다.

제출 유형을 버튼으로 변경하는 것이 가장 좋습니다.

+0

위의 것들이 다운로드 상황에 대한 문제를 제거하는 데 도움이되지 않습니다 ... 단지 양식을 제출하는 방법이 바뀌고 false를 반환하면 페이지가 완전히 중지됩니다. 컨트롤러에 ... – IyaTaisho

+0

오, 내 나쁜 내가 제출 한 모든 페이지에 대한 상쾌하다고 생각, 내가 그것에 대해 작업하자 – NikhilGoud