2012-09-07 2 views
0

나는 사용자가 내 웹 페이지에서 자신의 사용자 프로필에 업로드 할 이미지를 선택하는 시나리오가 있습니다. 내 웹 사이트에 .net의 MVC3 아키텍처를 사용하고 있습니다. 내가 원하는 것은 그가 원하는 것을 선택하고 데이터베이스에 저장하기 전에 이미지를 페이지에 표시하는 것입니다. 나는 주변 검색 및 내 친구가 그를 위해 일을 상기하는이 노력하고 결국 : 나는 시도 뷰에서JQuery를 사용하여 이미지를 동적으로로드하기

을 :

<div class="floatRight"> 
    <a onclick="opendialogbox('imageLoad2');" style="cursor: pointer">Photo</a> 
    <img src="… " width="16" height="16" id="imgThumbnail2" alt="photo" /> 
    <input type="file" name="imageLoad2" accept="image/*" id="imageLoad2" onchange="ChangeImage('imageLoad2','#imgThumbnail2')" hidden="hidden" /> 
</div> 

<script type="text/javascript"> 
    function opendialogbox(inputid) { 
     document.getElementById(inputid).click(); 
    } 

function ChangeImage(fileId, imageId) { 
     var ext = document.getElementById(fileId).value.match(/\.(.+)$/)[1]; 
     switch (ext.toLowerCase()) { 
      case 'jpg': 
      case 'bmp': 
      case 'png': 
      case 'gif': 
      case 'jpeg': 
       { 
        var myform = document.createElement("form"); 
        myform.style.display = "none"; 
        myform.action = "/ImagePreview/AjaxSubmit"; 
        myform.enctype = "multipart/form-data"; 
        myform.method = "post"; 
        var imageLoad; 
        var imageLoadParent; 
        //test browser used then submit form 
        $(myform).ajaxSubmit({ success: 
         function (responseText) { 
          var d = new Date(); 
          $(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds(); 
          if (document.all || is_chrome)//IE 
           imageLoadParent.appendChild(myform.firstChild); 
          else//FF      
           document.body.removeChild(myform); 
         } 
        }); 
       } 
       break; 
      default: 
       alert('Error, please select an image.'); 
     } 

    } 

</script> 

그리고 컨트롤러에 내가 시도 :

[AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult AjaxSubmit(int? id) 
     { 
      Session["ContentLength"] = Request.Files[0].ContentLength; 
      Session["ContentType"] = Request.Files[0].ContentType; 
      byte[] b = new byte[Request.Files[0].ContentLength]; 
      Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength); 
      Session["ContentStream"] = b; 
      HttpPostedFileBase file = Request.Files[0]; 
      string myFilePath = Server.MapPath(Url.Content("~/Content/themes/base/images/Auxiliar.png")); 
      file.SaveAs(myFilePath); 
      return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength); 
     } 



     public ActionResult ImageLoad(int? id) 
     { 
      byte[] b = (byte[])Session["ContentStream"]; 
      int length = (int)Session["ContentLength"]; 
      string type = (string)Session["ContentType"]; 
      Response.Buffer = true; 
      Response.Charset = ""; 
      Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      Response.ContentType = type; 
      Response.BinaryWrite(b); 
      Response.Flush(); 
      Response.End(); 
      Session["ContentLength"] = null; 
      Session["ContentType"] = null; 
      Session["ContentStream"] = null; 
      return Content(""); 
     } 

을 해주기를 이 모든 생각을 만들었지 만 내 웹 사이트에서 시도 할 때 메서드는 서버에 도달하지 못했습니다. 컨트롤러의 두 메서드 시작 부분에 중단 점을 배치했습니다. 여기

$(myform).ajaxSubmit({ success: 
         function (responseText) { 
          var d = new Date(); 
          $(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds(); 
          if (document.all || is_chrome)//IE 
           imageLoadParent.appendChild(myform.firstChild); 
          else//FF      
           document.body.removeChild(myform); 
         } 
        }); 

이 계속하지만 성공 조건을 입력 결코 : 나는 또한 선에 도달 할 때까지 페이지의 스크립트를 추적하는 파이어 폭스의 방화범을 사용했다. 페이지에 포함 된 JQuery 버전에 문제가있는 것 같았고 친구 사이트에 jquery-1.5.1.min.js, jquery-1.3.2.js 및 jquery_form.js가 포함되어 있음을 알게되었습니다.

이것들은 내 웹 사이트 (jquery-1.7.2.min.js를 사용하고있었습니다)에 있지만 문제는 계속되었습니다. jquery의 다양한 버전을 포함하면 메소드와 충돌이 발생하거나 문제가 다른 곳에서 발생하는지 확실하지 않습니다.

나는이 문제에 대해 큰 도움을 주실 것입니다. 미리 감사드립니다.

답변

0

Donnie, 여기에는 문제가 무엇인지 추론하기가 어렵지만 문제의 정확한 특성을 파악하기 위해 할 수있는 몇 가지 방법이 있습니다.

먼저, 성공 조건을 처리하고 있지만 위에서 쓴 것처럼 유사한 anon 함수로 오류 조건을 처리해야합니다. http://api.jquery.com/jQuery.ajax/이에 대한 몇 가지 정보를 가지고 있지만, 기본적으로는 쓸거야 :

$(myform).ajaxSubmit({ success: function (responseText) { 
            // your success method 
           }, 
         error: function (responseText) { 
            // your error method 
           } 
       }); 

다음, 방화 광 좋은,하지만 당신은 또한 네트워크 모니터링 기능뿐 아니라 스크립트 디버거있어 사용할 수 있습니다. 당신이 알지 못하는 곳에서 매우 관련있는 500 또는 404의 기회가있을 가능성이 있습니다. I까지 보통 새로운 var에

myform.action = "/ImagePreview/AjaxSubmit"; 

및 MVC 지금처럼 내 행동 URL을 만들어 보자 :가 404 인 경우

, 그것은이 라인과 관련이있을 수도로

var actionUrl = '@Url.Action("Action", "Controller")' 

모범 사례 일반적으로이 URL을 내보기 모델의 일부로 삽입하거나 숨겨진 필드의보기에 저장하지만 괜찮습니다.

희망 사항은 다음 도움말을 참조하십시오. 건배.

+0

시간 내 주셔서 감사합니다. 보내 주신 링크가 realizae의 한 가지 도움이되었습니다 ... $ (myform) .ajaxsubmit() 메소드는 jquery 라이브러리의 일부가 아니며 실제로는 jquery_forms 플러그인의 일부입니다. 이걸 들여다보고있어. 다시 한 번 감사드립니다. – Donnie

관련 문제