Tips on obtaining a byte array from within a JSON object

I am currently facing a challenge in retrieving a PDF file from the server, which is enclosed within a JSON object.

When I send a byte array of the PDF to the front-end, I can successfully read it by configuring the responseType to arraybuffer. Subsequently, I can proceed to download the PDF as follows:

var blob = new Blob([data], { type: application/pdf});
    if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
        $window.navigator.msSaveOrOpenBlob(blob);
    } else {
        var a = document.createElement("a");
        document.body.appendChild(a);
        var fileURL = URL.createObjectURL(blob);
        a.href = fileURL;
        a.download = fileName;
        a.click();
    }
}

However, when the server sends JSON with the byte array embedded within, setting the responseType to JSON poses a challenge in converting the blob. So, if I set the responseType to arrayBuffer, I receive an array of arrayBuffers. How can I convert this into JSON while still being able to extract the PDF afterwards?

The JSON structure that I receive is as follows:

{
  result: true,
  value: <the pdf byte array>,
  errorMessage: null
}

Answer №1

Converting bytes to base64 String is recommended, then you can read the bytes from it on the UI.

Answer №2

If we consider the variable below to represent the structure of the responseText:

responseText = {
      result: true,
      value: <the pdf byte array>,
      errorMessage: null
}

The byte array can be accessed using responseText.value. If the byte array is already in the form of a Uint8Array, then this method should work.

(Please note: There are other Typed Arrays available, so choose the most suitable one for your case):

var blob = new Blob([response.value], { type: 'application/pdf'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
} else {
    var a = document.createElement("a");
    document.body.appendChild(a);
    var fileURL = URL.createObjectURL(blob);
    a.href = fileURL;
    a.download = 'test';//filename
    a.click();
}

However, if the byte array is in the form of a string array or integer array, like below:

responseText.value = [145, 229, 216, 110, 3]

and it needs to be converted to a typed byte array, you can use the following code:

var ba = new Uint8Array(responseText.value);

or

var ba = new Uint8Array([145, 229, 216, 110, 3]);

Therefore,

var blob = new Blob([ba], { type: 'application/pdf'}); 

This method allows the byte array to be used for creating a blob, enabling the file to be downloaded when the click event occurs.

Answer №3

To transform a byte array into a string value, and vice versa, follow these steps: 1. Set the byte array value as a string. 2. When parsing the JSON data, convert the string back into a byte array.

For a practical example, refer to the following Java Byte Array Conversion Guide.

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

Getting the final element in a MySQL JSON array: Tips and tricks

After finally upgrading to MySQL 5.7, I've been exploring the new JSON functions and they are quite impressive! I encountered a scenario where I needed to retrieve the last element in a JSON array. It's simple when you know the ordinal position ...

how to open a new tab using JavaScript with Selenium

My code is supposed to open a new window that goes from the login window to the main menu, module, reports, and finally the report name. The report name should be opened in the next tab. Issue: The report name is not opening in a new tab; it's openin ...

Calling a JavaScript function using string parameters

Lately, I've stumbled upon an issue when attempting to execute a function with multiple arguments. <button type = "button" id = "clickmepls" onclick = killButton("clickmepls", "grave1")> Click me please </button> The definition of the fu ...

Displaying two distinct tables utilizing ng-repeat by employing customized directives

I'm facing an issue with a custom directive that generates tables and is appearing twice on my index page. The data for these tables comes from the $scope.globalrows variable. Even though globalrows contains 2 arrays, it always displays the second arr ...

Accessing data from API

Currently, I am attempting to retrieve data from a different API located at: In the past, I successfully extracted information using the Google Maps API with simplexml_load_file. However, when I tried to use the same approach for this new API, it did not ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

core.js:15723 ERROR TypeError: Unable to access the 'OBJECT' property because it is undefined

Whenever I attempt to run this function, I encounter an issue. My goal is to retrieve the latitude and longitude of an address from Google's API. This error message pops up: core.js:15723 ERROR TypeError: Cannot read property 'geometry' of ...

Converting Neo4j graph data into JSON format

I'm exploring various methods to utilize Neo4J graph data and showcase it on the internet. Currently, I am contemplating using a Java-based database reader that generates JSON output for web display. Is JSON a viable choice for presenting tree-like s ...

Exploring the Depths: A Guide to Selecting Nodes in Java Based on Depth

In my current JSON representation, I have the following structure: { "total": "555", "offset": "555", "hasMore": "false", "results": [ { "associations": { "workflowIds": [], "companyIds": [], "ownerIds": [], ...

Error Message for Tastypie FormValidation Issue

Within the scope of my current project, I have implemented TastyPies FormValidation for handling ModelResource. However, I am encountering an issue when attempting to transmit invalid data through an AJAX PUT request (utilizing AngularJS). For example: { ...

Prevent Mui popover from closing when clicking outside

Currently, I have implemented Mui Popover with ReactJS from the link here. One issue I am facing is that when a user clicks outside the popover, it automatically closes. Is there a way to disable this default behavior? Additionally, I would like to add a ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

Locate all nodes in neo4j that are connected to nodes matching a specified list of property values of a certain length

To clarify, I am interested in achieving the following (preferably using node/JS): Imagine you have a set of 3 job requirements ('JavaScript', 'PHP', 'MySQL'). In my graph setup, each Person node can be linked to multiple Sk ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: https://i.sstatic.net/PhJCE.jpg. Below i ...

Convert JSON to HTML tooltip content - hide brackets and include <br> tags

I am currently working with a JSON object in my JAVA code. I am trying to display the values of the object using the following HTML and AngularJS syntax: <uib-progress ng-if="month.data" data-toggle="tooltip" title="{{month.dataTest|json}}"> < ...

Modify the text highlighted in bold within the AngularJS application

In my angular.js application, I have a table that displays elements. The name of these elements sometimes needs to be displayed in bold by adding <b> and </b> tags. However, instead of rendering the name as HTML code, it is showing up as a stri ...

AngularJS is used to vertically collapse three different div elements. This feature

I am facing an issue with the design of my page that contains three panels. Two of these panels have tables, and when viewing the page on a smaller display, it disrupts the layout. I am wondering if there is a way to add collapsible buttons to the panels s ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...