Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the downloaded PDF file is corrupted.

var data = new FormData();
data.append('PARAM1', 'Value1');
data.append('PARAM2', 'Value2');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SERVICEURL');
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.onload = function() {
    
    console.log('Response text = ' + xhr.responseText);
    console.log('Returned status = ' + xhr.status);
    
    
    var arr = [];
    arr.push(xhr.responseText);

    var byteArray = new Uint8Array(arr);
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob(byteArray, { type: 'application/octet-stream' }));
    a.download = "tst.pdf";
    // Append anchor to body.
    document.body.appendChild(a)
    a.click();
    // Remove anchor from body
    document.body.removeChild(a)
    
};
xhr.send(data);

Answer №1

When requesting a binary file, it is crucial to notify XHR about it; otherwise, the default encoding will interpret pdf as text and cause encoding issues. Simply set the responseType property to 'blob' or specify the MIME type of pdf.

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // indicating that the response will be a pdf file

// OR xhr.responseType = 'application/pdf'; if the first method doesn't work

You can access it using the response property instead of responseText. Use arr.push(xhr.response); to receive a Blob object.

If this solution does not resolve the issue, feel free to let me know for an alternative approach.

Update:

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // specifying that the response will be a pdf file
xhr.onload = function() {
    var blob = this.response;
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(blob);
    a.download = "tst.pdf";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
};

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

Simple steps to validate an ajax response with a specific string

I'm encountering a problem with a simple ajax call that involves checking the returned text against a string: // in my php file echo 'mystring'; // in my javascript if((request.readyState == 4) && (request.status == 200)){ if(req ...

Ways to eliminate duplicate names within an object that contains multiple arrays

I have a set of data with different arrays and I need to remove any duplicate names that are being displayed. How can I accomplish this? Example of duplicate names The data is currently being output like this View all data The dsUserId values are repea ...

Is the purpose of express.json() to identify the Request Object as a JSON Object?

app.js const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const helloRouter = require('./routes/hello'); const app = express(); app.set(& ...

Incorporating marker tags to different sections of text within a contenteditable div

The main objective of this feature is to enable users to select placeholders within message templates (variable names enclosed in %). Inspired by Dribbble The API provides strings in the following format: "Hello %First_Name% %Middle_Name% %Last_Name% ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Enhance the numerical value displayed in jQuery UI tooltips

I have folders with tooltips displaying text like '0 entries' or '5 entries' and so on. I am looking for a way to dynamically update this tooltip number every time an item is added to the folder. The initial count may not always start a ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Leveraging the 'this' keyword in TypeScript

In my Javascript class, I used the 'this' keyword as shown below: if (this[this.props.steps[i].stepId].sendState !== undefined) { this.setState({ allStates: { ...this.state.allStates, [thi ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

I am having an issue with an input field not reflecting the data from the Redux state in my React app,

I am currently working on a todo list project using the MERN stack with Redux for state management. One issue I am facing is that the checkboxes for completed tasks are not reflecting the correct state from Redux when the page loads. Even though some tasks ...

The specified function is not recognized within the HTMLButtonElement's onclick event in Angular 4

Recently diving into Angular and facing a perplexing issue: "openClose is not defined at HTMLButtonElement.onclick (index:13)" Even after scouring through various resources, the error seems to be rooted in the index page rather than within any of the app ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

Encountering difficulty deserializing a JSONObject nested within a JSONArray in Java Spring

Here is the method I am working with: @RequestMapping(value = "/getFields", produces = "application/json") public Response getFields(@RequestParam(value = "id") int id) I have a subclass of Response that contains a JSONArray, which stores JSONObject inst ...

The initial io.emit message seems to always be delayed or lost in transmission

io.on('connection',function(socket){ console.log('connected'); socket.on('disconnect',()=>{ console.log('a user disconnected'); }); socket.on('sendMessage',function(data){ const message = data.te ...

Attempting to verify the HTML output, yet it remains unspecified

After developing a basic testing framework, I have set myself the challenge of creating a single-page web application using vanilla JavaScript. I've been facing difficulties in figuring out why my view test is not recognizing the 'list' con ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...