2015-02-06 64 views
0

我已經出現在文件服務器中的文件(例如:本地目錄E:\驅動器)下載文件C#

我有一個服務器端方法來下載文件

[System.Web.Services.WebMethod] 
    public static void DownloadFile(string AcctNum, string OfficeCode) 
    { 

     string fName = "E:\\FILES\\STATEMENTS\\sample.pdf"; 
     FileInfo fi = new FileInfo(fName); 
     long sz = fi.Length; 

     HttpContext.Current.Response.ClearContent(); 
     if (System.IO.Path.GetFileName(fName).EndsWith(".txt")) 
     { 
      HttpContext.Current.Response.ContentType = "application/txt"; 
     } 
     else if (System.IO.Path.GetFileName(fName).EndsWith(".pdf")) 
     { 
      HttpContext.Current.Response.ContentType = "application/pdf"; 
     } 
     else 
     { 
      HttpContext.Current.Response.ContentType = "image/jpg"; 
     } 


     HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(fName))); 
     HttpContext.Current.Response.AddHeader("Content-Length", sz.ToString()); 
     HttpContext.Current.Response.TransmitFile(fName); 
     HttpContext.Current.Response.Flush(); 
     HttpContext.Current.Response.End(); 
    } 

我從一個JavaScript函數調用此方法如下

function DownloadStatement(account,office) { 

     PageMethods.DownloadFile(account,office); 

    } 

DownloadFile()是獲取執行,但文件沒有得到通過瀏覽器下載。

我在這裏錯過了什麼。 請幫忙。

+0

當從Javascript調用上述方法時,不會觸發Page_load事件。這可能是文件沒有下載的原因嗎? – 2015-02-06 06:47:12

+0

爲什麼你在javascript中調用這個方法。僅用於頁面回發? – 2015-02-06 11:35:24

回答

0

嘗試this.put這在你的代碼下載

  string filePath = Server.MapPath("your filepath"); 
      FileInfo file = new FileInfo(filePath); 
      Response.Clear(); 
      Response.ClearHeaders(); 
      Response.ClearContent(); 
      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
      Response.AddHeader("Content-Length", file.Length.ToString()); 
      Response.ContentType = GetMimeType(file.Name); 
      Response.Flush(); 
      Response.TransmitFile(file.FullName); 
      Response.End(); 

而且這種方法添加到您的代碼來獲取文件類型。所以你不需要檢查文件類型

private string GetMimeType(string fileName) 
    { 
     string mimeType = "application/unknown"; 
     string ext = System.IO.Path.GetExtension(fileName).ToLower(); 
     Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); 
     if (regKey != null && regKey.GetValue("Content Type") != null) 
     { 
      mimeType = regKey.GetValue("Content Type").ToString(); 
     } 
     return mimeType; 
    } 
+0

請注意,我在DownloadFile()中使用靜態聲明,因爲我從JavaScript調用它也mimetype都工作正常。 – 2015-02-06 06:45:01

+0

此方法適用於服務器端。使用JavaScript,它不支持。 – 2015-02-06 11:33:50