萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

AJAX 流式檔案下載:隱藏 Form POST 實作範例

需求場景

AJAX 無法直接處理二進位檔案下載(瀏覽器不會彈出「另存新視窗」)。常見解法:動態建立隱藏 `

`,設定 `target="_blank"` 或 `target="hidden_iframe"`,提交至伺服器端點,伺服器回傳 `Content-Disposition: attachment` 觸發下載。

完整 jQuery 實作

$("#btnExport").on("click", function () {
    // 1. 建立隱藏表單
    var $form = $("", {
        style: "display:none",
        method: "post",
        action: "AjaxPost.aspx",      // 伺服器端點
        target: "_blank"              // 新分頁/視窗接收回應
    });

    // 2. 附加參數
    $("", { type: "hidden", name: "type",  value: "Export" }).appendTo($form);
    $("", { type: "hidden", name: "fileId", value: currentFileId }).appendTo($form);

    // 3. 加入 DOM、提交、移除
    $("body").append($form);
    $form.submit();
    $form.remove();
});

伺服器端關鍵回應標頭 (C# 範例)

public void ProcessRequest(HttpContext context)
{
    if (context.Request["type"] == "Export")
    {
        string fileId = context.Request["fileId"];
        byte[] fileBytes = GenerateExcel(fileId); // 產生檔案位元組陣列

        context.Response.Clear();
        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.AddHeader("Content-Disposition", "attachment; filename=Export.xlsx");
        context.Response.BinaryWrite(fileBytes);
        context.Response.End();
    }
}

進階:使用 `