Asp.net

通過呼叫 .ashx 頁面下載文件

  • February 28, 2020

我從母版頁客戶端腳本 (Jquery) 請求 .ashx 頁面,該腳本具有下載 PDF 文件的程式碼。當我調試它時,我可以看到“文件下載”程式碼的執行,但文件沒有下載。

$.ajax({
   type: "POST",
   url: "FileDownload.ashx",
   dataType: "html",
   success: function (data) { }
} );

public class FileDownload : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
       //context.Response.ContentType = "text/plain";
       //context.Response.Write("Hello World");

       string fileName = "BUSProjectCard.pdf";
       string filePath = context.Server.MapPath("~/Print/");
       context.Response.Clear();
       context.Response.ContentType = "application/pdf";
       context.Response.AddHeader("Content-Disposition", "attachment; filename="+fileName);
       context.Response.TransmitFile(filePath + fileName);
       context.Response.End();
   }

您的文件正在下載,但您在 javascript 上通過data呼叫參數獲取它,因為您使用 Ajax 呼叫它。

您使用處理程序 - 所以這裡不需要 ajax,使用 javascript 最簡單的事情是:

window.location = "FileDownload.ashx?parametres=22";

或使用簡單的連結作為

 <a target="_blank" href="FileDownload.ashx?parametres=22" >download...</a>

啊,通過url發送參數,你不能那樣發布它們。

您還可以閱讀:從伺服器下載文件的最佳方式是什麼

引用自:https://stackoverflow.com/questions/12087040