AJAXでファイルをダウンロードする

環境

HTML5に対応したブラウザ

やり方

汎用的にfunctionを作ってみた。

function downloadFile(ajaxUrl, ajaxData, fileName) {
    $.ajax({
        type: "post",
        url: ajaxUrl,
        data: ajaxData,
        xhrFields: { responseType: 'blob' }
    }).done(function (response, _textStatus, _jqXHR) {
        if (window.navigator.msSaveBlob) {
            // IE
            window.navigator.msSaveBlob(response, fileName);
        } else {
            // IE以外
            $('<a>', {
                href: URL.createObjectURL(new Blob([response], { type: response.type })),
                download: fileName
            }).appendTo(document.body)[0].click();
        }
    });
}

// 使い方
downloadFile("/download", $('form').serialize(), "download.zip");

説明

xhrFields: { responseType: 'blob' }$.ajaxでバイナリデータを受け取るために必要なパラメーター。

参考

qiita.com