I am receiving a data buffer from an node/express endpoint on my client side and I want to convert the buffer into a file.
The file may be a pdf, text document, or image. The only information the endpoint tells me is that it's sending an octet stream.
How do I go about doing this?
This is the code I have so far on my client side
const xhr = new XMLHttpRequest();
xhr.open("POST", "MY_URL", true);
xhr.responseType = "arraybuffer";
// I need to send some data for the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// send request
xhr.send(`identifier=${myIdentifier}`);
xhr.onload = function (xEvent)
{
const arrayBuffer = xhr.response;
if (arrayBuffer)
{
const byteArray = new Uint8Array(arrayBuffer);
const url = window.URL.createObjectURL(new Blob([byteArray]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "file.pdf"); //or any other extension
document.body.appendChild(link);
link.click();
}
};