Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt.

My approach involves using JavaScript and vue.js.

Function responsible for calling the server and retrieving the byte array:

function getManualAcademico(id) {
        const url = '/Sec/Ent/Get?d=';

        window.config.axios.get(url + id)
            .then(function (response) {
                var manualAcademico = response.data;

                Here I am invoking a function to download the PDF by passing in the response data (an array of bytes).
                DownloadPDF(manualAcademico);
            })
            .catch(function(error) {
                logInConsole(error);
            });
    }


    function DownloadPDF(manualAcademico) {
        var byteArray = new Uint8Array(manualAcademico.manual.$value);
        var a = window.document.createElement('a');
        a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));
        a.download = "ManualAluno.pdf";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

Regarding the server side code:


[EnableCors(origins: "*", headers: "*", methods: "*")]
public IHttpActionResult Get(int Id)
{
    return Ok(new
    {
        manual = SEC.Get(Id)
    });
}

The download process seems to be successful, but the resulting file is corrupted. Any suggestions or insights on how to resolve this issue would be greatly appreciated.

Thank you.

Answer №1

Consider including responseType: 'arraybuffer' in the request.

For example:

window.config.axios.get({url: url + id, responseType: 'arraybuffer'})..  

This approach can be helpful.

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

Can a directive be designed to function as a singleton?

Our large single page app includes a directive that is utilized in various locations across the page, maintaining its consistent behavior and appearance each time. However, we are experiencing an issue with this directive due to the ng-repeat it contains, ...

Error in React Native: Press function is not defined for TextInput

I am currently working on implementing an increment and decrement button feature in my application, which should then display the updated number in a text input field. However, I seem to be facing an issue where the text input is not showing the expected o ...

Tips for dynamically loading a different component based on route parameters with the VueJS Router

I'm searching for the best way to dynamically load a different VueJS component based on the presence of props in a route. For instance, navigating to /users would display the users list page, while going to /users/1 will take you to the user ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

Tips on retrieving a <list> from an MVC controller and passing it to the view with jQuery and AJAX

How can I retrieve a list from an MVC controller to a view using jQuery AJAX without getting the error message [object Object]? Here is my AJAX code: $.ajax({ type: 'POST', contentType: 'application/json; ch ...

Using AJAX to Query a PHP Database

Currently, I am implementing an AJAX call from the YouTube player JavaScript to a PHP page that contains various functions, mainly involving database inserts. In my PHP code, I use a case statement to determine which function is being called based on the d ...

Stop ScrollViewer from altering its Content dimensions

My main requirement for the ScrollViewer is to allow scrolling only, without enabling its Content to grow. However, it seems that the content does expand. How can I prevent this? <ScrollViewer VerticalScrollBarVisibility="Auto" > <Gr ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Building a versatile assortment of items inside a larger group

I am working on creating a collection that contains a collection in two classes. Here is the code I have written so far: public class GenericReportInfo { public string ReportName { get; set; } public string ReportFileName { get; set; } public ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

Using .NET to write SQL Server by sending declared strings as queries

I am encountering difficulties in sending the "hisname" and "hisage" declared variables as a query in this project demo. Each time a user inputs a name and age, I need to send them as separate queries to the database. static void Main() { stri ...

Changing a button's text in Vue.js when holding a keyboard modifier - how to do it!

While working with Vue, I am attempting to modify a button's behavior when the Shift key is pressed. Adjusting the behavior of the click event was straightforward: @click.exact="goForward" @click.shift="goBackward" However, I am f ...

Firebase Auth in Vue.js is having trouble accurately verifying error messages when resetting passwords

As I work on sending a password reset email to a user, Firebase throws an error called RESET_PASSWORD_EXCEED_LIMIT when the number of requests goes beyond a certain limit. I am attempting to capture this error message in order to notify the user that thei ...

Utilizing JavaScript to access and present results from a PHP file located on a separate server

UPDATE I have set the header of my php file as shown below: header("Access-Control-Allow-Origin: *"); Currently, this is the error I am seeing in my browser: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Heade ...

Guide to displaying a function result in Vue 3

I have just started learning vue js and I am facing an issue. I want to display the value returned by the following function in a table row: The function is: getGroup(id){ this.users.forEach(element =>{ if(element.id===id) ...

Relying on external components within the .NET Framework assembly in an indirect manner

After updating my Telerik dll's by replacing them with the new ones and cleaning my solution, I encountered the following error: Warning 3 The primary reference "Telerik.Windows.Documents.FormatProviders.Xaml" could not be resolved due to an indire ...

Utilize AJAX or another advanced technology to refine a pre-existing list

I am trying to implement a searchable list of buttons on my website, but I haven't been able to find a solution that fits exactly what I have in mind. Currently, I have a list of buttons coded as inputs and I want to add a search field that will filte ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...