在415 http代码上将ajax Post查询转换为XHR结果

时间:2018-12-14 15:38:38

标签: javascript ajax xmlhttprequest

我在使用ajax下载文件时遇到问题,有人告诉我使用XhmlHttpRequest(XHR)将有助于解决该问题,因此我试图将旧的ajax rest请求转换为新的xhr rest请求

不幸的是,我还没有成功,我得到415 HTTP错误代码,它指示未支持的媒体类型req.send(JSON.stringify(printData));,而chrome正在高亮我的代码部分,下面将对此进行介绍。

这是我的ajax电话

var jsonData = JSON.parse(JSON.stringify(printData));
                var settings = {
                    "async": true,
                    "crossDomain": true,
                    "url": "http://" + document.location.host + "/facturation/print/client",
                    "method": "POST",
                    "headers": {
                        "cache-control": "no-cache",
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    "processData": false,
                    "contentType": "application/json",
                    xhrFields: {
                        responseType: 'blob'
                    },
                    "dataType": "text",
                    "data": JSON.stringify(printData)
                }

                $.ajax(settings).done(function(response, status, xhr) {
                    console.log(response);
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');

                    if (disposition) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }
                    var linkelem = document.createElement('a');
                    try {
                        var blob = new Blob([response], {
                            type: 'application/octet-stream'
                        });

                        if (typeof window.navigator.msSaveBlob !== 'undefined') {
                            //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                            window.navigator.msSaveBlob(blob, filename);
                        } else {
                            var URL = window.URL || window.webkitURL;
                            var downloadUrl = URL.createObjectURL(blob);

                            if (filename) {
                                // use HTML5 a[download] attribute to specify filename
                                var a = document.createElement("a");

                                // safari doesn't support this yet
                                if (typeof a.download === 'undefined') {
                                    window.location = downloadUrl;
                                } else {
                                    a.href = downloadUrl;
                                    a.download = filename;
                                    document.body.appendChild(a);
                                    a.target = "_blank";
                                    a.click();
                                }
                            } else {
                                window.location = downloadUrl;
                            }
                        }

                    } catch (ex) {
                        console.log(ex);
                    }
                })

我尝试使用XHR的是下面的

        var req = new XMLHttpRequest();
        req.open("POST", "http://" + document.location.host + "/facturation/print/client", true);
        req.responseType = "blob";
        req.setRequestHeader("cache-control", "no-cache");
        req.setRequestHeader("contentType", "application/json");
        req.setRequestHeader("dataType", "text");
        req.setRequestHeader("X-CSRF-TOKEN", $('meta[name="csrf-token"]').attr('content'));

        req.onload = function(event) {
            var blob = req.response;
            console.log(blob.size);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "Dossier_" + new Date() + ".pdf";
            link.click();
        };

        req.send(JSON.stringify(printData));

我应该怎么做才能使这项工作成功?

1 个答案:

答案 0 :(得分:1)

在代码的所有位置,标头都应为"Content-Type"而不是"contentType"