node -e 'console.log(process.versions.v8)'
I had a REST Jersey application deployed in Tomcate that emitted binary data. E.g. something along the following lines:
@Path("/file/{i}") @GET @Produces({"application/octet-stream"}) public Response getFile(@PathParam("i") int i) throws Exception { System.out.printf("Requesting the content of file with i = %d\n", i); ...
I then wanted a React app (but really could have been vanilla JavaScript) to invoke that REST service and obtain the file data (which could have been either text or binary).
The first problem to solve is CORS. For that see: this note of mine.
Following that I have tested the following code to work well with both text and binary files:
const URL = `http://localhost:8080/radacer-oaipmh/jax-rs/oaipmh/file/${this.props.iDB}`; console.log(`doing Ajax on ${URL}`); var oReq = new XMLHttpRequest(); oReq.open("GET", URL, true); oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); if (false) { for (var i = 0; i < byteArray.byteLength; i++) { // do something with each byte in the array console.log(byteArray[i]); } } const blob = new Blob([byteArray], {type: "application/octet-stream"}); saveAs(blob, this.props.fname); } }.bind(this); oReq.send(null);
Note that the code above also saves the binary file locally but obviously once you got the bytes you can do pretty much whatever you like.
Since this is from a webpack application I install the necessary support for the filesaver.js-npm module with:
npm i -S filesaver.js-npm
And then, from JavaScript:
import {saveAs} from 'filesaver.js-npm';