2014-04-01 34 views
1

我在我的服務器中有一個word文檔,我想發送給我的客戶端。其實我希望他們下載該文件。我在運行時創建該文件,並且我想在從服務器下載它之後將其刪除。我在本地嘗試這種情況。創建文件後,我的服務器將其發送給客戶端。在Web瀏覽器中我看到這一點:發送文件給客戶端並將其刪除

enter image description here

我不想這樣。我希望Web瀏覽器打開保存文件對話框。我希望客戶端下載真實文件。這裏是我的代碼:

  Guid temp = Guid.NewGuid(); 
      string resultFilePath = Server.MapPath("~/formats/sonuc_" + temp.ToString() + ".doc"); 
      if (CreateWordDocument(formatPath, resultFilePath , theLst)) { 

       Response.TransmitFile(resultFilePath); 

       Response.Flush(); 

       System.IO.File.Delete(resultFilePath); 

       Response.End(); 
      } 

回答

6

這段代碼應該可以做到,但注意到這會導致將整個文件加載到服務器的內存中。

private static void DownloadFile(string path) 
{ 
    FileInfo file = new FileInfo(path); 
    byte[] fileConent = File.ReadAllBytes(path); 

    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name)); 
    HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); 
    HttpContext.Current.Response.ContentType = "application/octet-stream"; 
    HttpContext.Current.Response.BinaryWrite(fileConent); 
    file.Delete(); 
    HttpContext.Current.Response.End(); 
} 
1

你想要的是不是一個.aspx文件(這是一個網頁),但一個.ashx它可以提供你所需要的數據,並設置內容處置。見爲例此問題(這裏使用PDF的下載):

Downloading files using ASP.NET .ashx modules

您也可以嘗試設置正確的內容類型/ MIME類型的Word,也許像下面,否則可能會take a look at this question

response.ContentType = "application/msword"; 
response.AddHeader("Content-Disposition", "attachment;filename=\"yourFile.doc\""); 
+0

既然你提到了,我一直在關注這個例子:http://davidarodriguez.com/blog/2013/05/29/downloading-files-from-a-server-to-client-使用-asp-net-when-file-size-is-too-big-for-memorystream-using-generic-handlers-ashx /但是必須將文件名傳遞給.ashx類? – MilesDyson

+1

您可以將一個名稱傳遞給.ashx,或者讓ashx從某處獲取該文件。重點是您必須指定要傳輸到客戶端/瀏覽器的數據類型,以及您希望如何處理這些數據,這是通過指定內容類型和標題來完成的。 – Kjartan

相關問題