How to transform an array of bytes into a file in NodeJS or AngularJS

A third party API sends me a file in the form of a byte array e.g.

(244511) [37, 80, 68, 70, 45, 49, 46, 52, 13, 10, 37, 226, 227, 207, 211, 13, 10, 49, 32, 48, 32, 111, 98, 106, 13, 10, 60, 60, 13, 10, 47, 84, 105, 116, 108, 101, 32, 60, 70, 69, 70, 70, 48, 48, 52, 69, 48, 48, 55, 53, 48, 48, 54, 70, 48, 48, 55, 54, 48, 48, 54, 70, 48, 48, 50, 48, 48, 48, 53, 50, 48, 48, 54, 49, 48, 48, 55, 48, 48, 48, 55, 48, 48, 48, 54, 70, 48, 48, 55, 50, 48, 48, 55, 52, 48, 48, 54, 70, 62, 13, …]

I know the file’s original name (extension included) but not the mime type.

My backend (NodeJS) currently does this:

const data = JSON.parse(res.body).result[0] // 'data' is the byte array above
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end({ data })

My frontend (AngularJS 1.x) does this:

var data = rsp.data
var blob = new $window.Blob([data], {type: 'application/pdf;charset=utf-8'})
$window.saveAs(blob, filename)

(the application/pdf part I added a few minutes ago to see it would make it work for PDF files at least… it doesn’t)

I really have no idea what I’m supposed to do to turn that array into a file that gets opened correctly, I’ve tried everything I’ve managed to find online to no avail. A file gets saved, but it won’t work when opened.

I don’t even know whether I have to change my frontend or my backend, or both.

Any help will be much appreciated.

Answer

The solution was to first cast the byte array to Uint8Array on the frontend. Also, specifying the mime type when creating the blob is unnecessary apparently, which is very handy.

var bytes = new Uint8Array(rsp.data)
var blob = new $window.Blob([bytes])
$window.saveAs(blob, filename)

Leave a Reply

Your email address will not be published. Required fields are marked *