2012-08-23 3 views
4

나는 웹 메서드 을 통해 서버에서 파일을 다운로드하려고했지만 나에게 적합하지 않습니다. 을 다운로드하는 방법을 모른다Ajax 호출을 통해 웹 메서드를 통해 C# 파일을 다운로드 하시겠습니까?

..

 [System.Web.Services.WebMethod()] 
public static string GetServerDateTime(string msg) 
{ 
    String result = "Result : " + DateTime.Now.ToString() + " - From Server"; 
    System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\\" + "Default.aspx"); 
    System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; 
    Response.ClearContent(); 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
    Response.AddHeader("Content-Length", file.Length.ToString()); 
    Response.ContentType = "application/octet-stream"; 
    Response.WriteFile(file.FullName); 
    //HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    Response.Flush(); 
    Response.End(); 
    return result;   
} 

내 아약스 호출 코드를 아래로 내 코드는

<script type="text/javascript"> 
    function GetDateTime() { 
        var params = "{'msg':'From Client'}"; 
        $.ajax 
         ({ 
          type: "POST", 
          url: "Default.aspx/GetServerDateTime", 
          data: params, 
          contentType: "application/json;charset=utf-8", 
          dataType: "json", 
          success: function (result) { 
           alert(result.d); 
          }, 
          error: function (err) { 

          } 
         }); 
    } 
</script> 

다음과 같이 내가 버튼 클릭에서이 기능이라고했다 다른 방법을 사용하는 파일

다른 방법을 사용할 수 있다고 제안하거나 동일한 코드에서 수정하십시오. 모든

덕분에 ..

답변

8

의 WebMethod는 현재 응답 스트림을 제어하지 않기 때문에이이 방법을 수행 할 수 없습니다. 자바 스크립트에서 웹 메소드를 호출 할 때, 응답 스트림은 이미 클라이언트에 전달되었으며, 사용자가 할 수있는 방법은 없습니다.

이 옵션은 WebMethod가 파일을 서버의 실제 파일로 생성 한 다음 생성 된 파일에 url을 호출하는 javascript로 보내고, 호출 JavaScript는 window.open(...)을 사용하여 엽니 다.
실제 파일을 생성하는 대신 WebMethod에서 처음 시도한 내용에 대한 GenerateFile.aspx를 호출 할 수 있지만 Page_Load에서 수행하고 window.open('GenerateFile.aspx?msg=From Clent')을 javascript에서 호출 할 수 있습니다.

3

웹 메서드를 호출하는 대신 일반 처리기 (.ashx 파일)를 사용하고 파일을 처리기의 ProcessRequest 메서드에 다운로드하는 코드를 넣는 것이 좋습니다.

2

이 C 번호 뒤에 아약스 전화

   $(".Download").bind("click", function() 
      { 
       var CommentId = $(this).attr("data-id"); 
       $.ajax({ 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        url: "TaskComment.aspx/DownloadDoc", 
        data: "{'id':'" + CommentId + "'}", 
        success: function (data) { 


        }, 
        complete: function() { 

       } 
      }); 
     }); 

코드

[System.Web.Services.WebMethod] 
    public static string DownloadDoc(string id) 
    { 
     string jsonStringList = ""; 
     try 
     { 
     int CommentId = Convert.ToInt32(id); 
     TaskManagemtEntities contextDB = new TaskManagementEntities(); 
     var FileDetail = contextDB.tblFile.Where(x => x.CommentId == CommentId).FirstOrDefault(); 
     string fileName = FileDetail.FileName; 
     System.IO.FileStream fs = null; 
     string path = HostingEnvironment.ApplicationPhysicalPath + "/PostFiles/" + fileName; 
     fs = System.IO.File.Open(path + fileName, System.IO.FileMode.Open); 
     byte[] btFile = new byte[fs.Length]; 
     fs.Read(btFile, 0, Convert.ToInt32(fs.Length)); 
     fs.Close(); 
     HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + fileName); 
     HttpContext.Current.Response.ContentType = "application/octet-stream"; 
     HttpContext.Current.Response.BinaryWrite(btFile); 
     HttpContext.Current.Response.End(); 
     fs = null; 
     //jsonStringList = new JavaScriptSerializer().Serialize(PendingTasks); 
    } 
    catch (Exception ex) 
    { 

    } 
    return jsonStringList; 
} 
+0

당신은 더 설명을 쓸 수있다? – Tacet

+0

이 코드의 어느 부분을 알고 싶으십니까? 나는 당신에게 설명을 할 것이다 –

+0

파일을 다운로드 할 수 없다. : ( –

관련 문제