javascript 下载 application/octet-stream 文件

function downloadFile(id) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://localhost/api/app/isp-detection/' + id + '/download');
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/octet-stream');
    xhr.onload = function () {
        if (xhr.status === 200) {
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(xhr.response);
            console.log(url);
            a.href = url;
            a.download = id + '.xlsx';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        }
    };
    xhr.send();
}

 或

function downloadFile(id) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://isp-system.vtmarkets.net/api/app/isp-detection/' + id + '/download');
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (xhr.status === 200) {
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(xhr.response);
            var defaultFileName = xhr.getResponseHeader("Content-Disposition").split(";")[1].split("filename=")[1];
            var filename = decodeURI(defaultFileName);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        }
    };
    xhr.send();
}

 

posted @ 2024-02-07 17:52  -H&H-  阅读(848)  评论(0)    收藏  举报