2013-08-06 34 views
0

目前我正在試圖解決了以下問題:發送PDF格式的瀏覽器(如附件)

 var fileName = "monthly_report.pdf" 
     var document = new Document(); 
     //DO SOME STUFF WITH THE DOCUMENT 

     MemoryStream stream = new MemoryStream(); 
     doc.Save(stream, SaveFormat.Pdf); 
     byte[] bytes = stream.GetBuffer(); 
     Response.Clear(); 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("content-disposition", "attachment; filename="+fileName); 
     Response.BinaryWrite(bytes); 
     Response.End(); 

在此基礎上的代碼我試圖顯示的Aspose。單詞文檔在瀏覽器中轉換爲pdf /試圖在瀏覽器中爲所述文檔創建下載對話框。

當我執行操作時沒有錯誤消息。然後pdf的內容顯示在chrome調試器的響應消息中。答覆也保持適當的大小(pdf爲60kb)。它根本不會開始下載或在瀏覽器中顯示PDF,我不知道爲什麼會這樣。

我也試圖通過閱讀Aspose提供一種替代方案:這會導致顯示在響應而不是瀏覽器本身的PDF格式完全相同的結果

 var resp = System.Web.HttpContext.Current.Response; 
     resp.Clear(); 
     // Create Memory Stream Object 
     MemoryStream stream = new MemoryStream(); 
     doc.Save(stream, SaveFormat.Pdf); 
     doc.Save(resp, fileName, ContentDisposition.Attachment,        SaveOptions.CreateSaveOptions(
     SaveFormat.Pdf)); 
     resp.End(); 

執行此代碼的控制操作由AJAX聲明呼籲:

$("#btnReport").click(function() { 

      var datum = $("#hiddenDatum").val(); 

      $.ajax({ 
       type: "GET", 
       url: '@Url.Action("GenerateMonthlyReport", "Reporting")', 
       data: { datum: datum}, 
       success: function (data) { 

       } 
      }); 
     }); 

任何建議,以我在做什麼錯將高度讚賞。

編輯:我的研究表明,ajax調用確實不起作用。我如何根據我的控制器邏輯啓動文件下載?

+0

不要爲此使用ajax請求。 –

+0

如何在JavaScript中啓動下載? – user1950859

回答

0

您無法使用AJAX調用直接下載文件。你可以這樣做,但:

$.ajax({ 
    type: "GET", 
    url: '@Url.Action("GenerateMonthlyReport", "Reporting")', 
    data: { datum: datum}, 
    success: function (data) { 
     window.location.href = data.filePath; // i.e. '/downloads/file.pdf'; 
    } 
}); 

不能流數據返回到jQuery的處理程序。爲什麼不簡單地用一個標準的HTML錨點做這個簡單的獲取請求?

@Html.ActionLink("Generate Monthly Report", "GenerateMonthlyReport", "Reporting", new { datum = DateTime.Now.ToString("d", new CultureInfo("en-US")}) 
相關問題