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

Using JavaScript, you can filter an array of objects based on a specific search input

I am in the process of implementing a filtering feature for a list using React, but surprisingly, I haven't been able to find any useful resources online to guide me through this common task. Currently, I have an array of users that I need to filter ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

Cherrypy/Chrome: Issue with jquery ajax request remaining pending after several successful requests

My current project involves a Cherrypy server that receives a JSON array from a client via AJAX call. The server then manipulates the array and sends it back to the client. However, I've noticed an issue where after a few smooth requests, the next req ...

Changing the image source using Javascript and extracting part of the URL

i'm attempting to extract the image url from a series of urls in a loop, removing the hash portion () without the hash (?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDi79vN15idfFETvntyC9yat7FvZQ). I've managed to mak ...

Using CSS to Create Text Wrapping

I have a massive string of randomly generated numbers that I am trying to display in a div block. Since the string is quite long, it's currently being shown in one single line. For instance: String str="13,7,5,1,10,7,18,11,17,10,9,16,17,9,6,19,6,13, ...

Fire an event following the execution of $state.go()

Is there a way to activate an event once the state has been modified in ui.router? Specifically, I am utilizing the ionic framework alongside angularJS which incorporates angular-ui-router. Note: Below is the pseudo code I am hoping to implement. $state. ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

"Unexpected compatibility issues arise when using TypeScript with React, causing errors in props functionality

Just the other day, my TypeScript+React project was running smoothly. But now, without making any changes to the configurations, everything seems to be broken. Even rolling back to previous versions using Git or reinstalling packages with NPM does not solv ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Having trouble with the error "vue-cli-service ENOENT not found" after updating Vue CLI?

Yesterday, I encountered errors in my Vue project. Initially, I thought it was a node-related issue as my project was not loading properly, which was unusual. Additionally, I kept receiving an audit problem related to my CLI plugin. After updating Node to ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...