用于在字节数组中显示PDF文件的JavaScript代码(不是base64编码)

时间:2016-05-12 08:40:36

标签: javascript asp.net rest browser

我正在使用ASP .NET Web API,其中API的POST函数在C#代码中返回一个像这样的字节数组:

return Ok(outputStream.ToArray());

其中outputStream的类型为System.IO.MemoryStream,ToArray()返回一个字节数组。

此功能正在返回我想在浏览器中向用户显示的PDF流,或至少让他们保存。

我遇到了来自Stack Overflow的JavaScript example,它显示了如何从Base64编码的字符串中获取Blob并显示它,当API返回Base64编码的字符串时,我能够使其工作;但是,当API返回如前所示的字节数组时,我无法使其工作。

我可以获得一些代码示例,说明如何在API返回字节数组时使其工作吗?

1 个答案:

答案 0 :(得分:0)

我的JQuery Ajax POST请求如下所示:

function LoadPDF() {
        var args = [];
        var x = $.ajax({
            type: "POST",
            url: "DirectoryQuery.aspx/GetFullPdf",
            contentType: "application/json; charset=UTF-8",
            responseType: "text/plain; charset=UTF-8",
            async: true,
            dataType: "json",                             
            processData: "false",
            success: OnSuccess,
            error: OnErrorCall
        }); 
        function OnSuccess(response) {
            var byteArray = new Uint8Array(response.d);

            saveTextAsFile("document.pdf", byteArray);
        }
        function OnErrorCall(response) {
            console.log(response);                
            //location.reload();
        }
    }

尝试file-save-as.js,如下所示:

function saveTextAsFile(fileNameToSaveAs, textToWrite) {
    /* Saves a text string as a blob file*/
    var ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
      ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
      ieEDGE = navigator.userAgent.match(/Edge/g),
      ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));

    if (ie && ieVer < 10) {
        console.log("No blobs on IE ver<10");
        return;
    }

    var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain'
    });

    if (ieVer > -1) {
        window.navigator.msSaveBlob(textFileAsBlob, fileNameToSaveAs);

    } else {
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = function (e) { document.body.removeChild(e.target); };
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
        downloadLink.click();
    }
}