Displaying a PDF file in a browser using a byte array with JavaScript without the need for base64 encoding

I am currently dealing with an ASP .NET Web API where the POST function is sending back a byte array in C# code like this:

return Ok(outputStream.ToArray());

outputStream is of type System.IO.MemoryStream and ToArray() returns a byte array.

The purpose of this function is to send a PDF stream that I want users to view in their browser or download.

I found a JavaScript example on Stack Overflow explaining how to extract a Blob from a Base64 encoded string for display. I was successful in implementing it when the API returned a Base64 encoded string, but struggled when it returned a byte array as shown above.

Could someone provide me with some code samples on how to make it work when the API sends back a byte array?

Answer №1

Here is the code for my JQuery Ajax POST request:

function LoadPDF() {
        var parameters = [];
        var request = $.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: handleSuccess,
            error: handleError
        }); 
        function handleSuccess(data) {
            var pdfContent = new Uint8Array(data.d);

            saveFile("document.pdf", pdfContent);
        }
        function handleError(data) {
            console.log(data);                
            //location.reload();
        }
    }

You can try using file-save-as.js for saving files like below:

function saveFile(fileName, content) {
    /* Saves a text string as a blob file */
    var ieBrowser = navigator.userAgent.match(/MSIE\s([\d.]+)/),
      ie11Browser = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
      edgeBrowser = navigator.userAgent.match(/Edge/g),
      browserVersion = (ieBrowser ? ieBrowser[1] : (ie11Browser ? 11 : (edgeBrowser ? 12 : -1)));

    if (ieBrowser && browserVersion < 10) {
        console.log("Blob not supported on IE version less than 10");
        return;
    }

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

    if (browserVersion > -1) {
        window.navigator.msSaveBlob(fileBlob, fileName);

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message displays "window.addEventListener is not a function", indicating that

Recently, I've been dealing with this code snippet: $(document).ready(function(){ $(window).load(function() { window.addEventListener("hashchange", function() { scrollBy(0, -50);}); var shiftWindow = function() { scrollBy(0, - ...

Turn off client certificate validation in IIS 10 for an Asp.net site while enabling the application to request client certificates from incoming connections

When I host my Asp.net API website on IIS 10, I encounter an issue with custom client certificate validation. The failed request logs show the following message when I make calls to my API: A certificate chain was processed, but it terminated in a root ...

Internet Explorer struggling to function due to JavaScript errors

While Chrome and Firefox breeze through the page, it seems to hang for an eternity in Internet Explorer. Here is the problematic page: ============= Error Details: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2 ...

Launching a ASP.net Website directly from the main directory

I am developing a website using ASP.net. All the content for my project is stored in a folder named MyWebSite. Whenever I launch my application from Visual Web Developer 2008, the browser shows the address http://localhost/MyWebSite/Default.aspx in the a ...

In JavaScript, find a value in an array and substitute it with the value from the

One of my tasks involves manipulating a string variable in the following manner: domNodes += '<a href="javascript: void(0);" data-role="node_jump" data-node="'+this.tagName.toLowerCase()+'">'+this.tagName + "</a>" + " & ...

Restricting the ability to uncheck jQueryCheckboxes

I have a unique scenario where I have two forms located in different tabs. Each crossover field has the ability to duplicate its value to the other form when there is a change in the field's content. In addition, I have implemented a feature where th ...

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

Suggestions for preventing the highlighting of the space between buttons on a webpage

html: <button id='automoney' onclick='minusTen()'></button> <button id='automoney2' onclick='minusHundred()'></button> <button id='automoney3' onclick='minusFiveHundred()& ...

Error: The requested resource does not have the 'Access-Control-Allow-Origin' header. The request is successful, but an error is being triggered

As I am trying to make an Ajax cross domain request, I have come across a strange issue. In the console of Chrome dev tools, I see the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource" Despite this ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

Unlocking the power of AngularJS scopes

I am currently in the learning stages of AngularJS and am working on a personal project that involves fetching JSON data and displaying it on an HTML page using AngularJS. The main objective is to have two columns, "rules" and "servername", with checkbox i ...

Assign a value to a dropdownlist in Javascript

I am facing an issue with setting the selected value of a dropdownlist that is populated by a webservice using ajax cascading dropdown. It seems like the values are not available when the javascript code runs, even though I have placed it at the bottom o ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

Reloading and redirecting web pages with PHP and Ajax techniques

I am currently working on a registration form in PHP. I have implemented validations for the input fields and used AJAX to handle the form submission. Everything seems to be functioning properly, except that when the submit button is clicked, the success ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...

Exploring and accessing elements and nested objects within a dynamically named element in JavaScript using JSON syntax

Receiving a JSON response from an API, here's what the data looks like: [{ "order_id":"1111", "restaurant_id":"ABC", "fullfillment":"Delivery", "order_channel":" ...

What is the most efficient method for obtaining Raw XML from a URL in .NET other than using WebClient or HttpWebRequest?

Currently, I am developing a Geocoding application that involves inputting an address into the URL and extracting the XML response. In order to complete this project, I require the entire XML data. Are there alternative classes available for downloading ...

React - Received an unexpected string containing a template expression with no curly braces present in the string

Currently, I am enrolled in a React tutorial online. I have inputted the code exactly as it was shown on the screen. Strangely, it seems to be working perfectly fine in the video but not when I try it myself. Below is the code snippet: <Link to={&apos ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...