Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6632

NodeJS: View and download a PDF from array buffer

My issue:

I already have a solution where I can view a pdf file from an array buffer like so:

const data = getArrayBufferFromAPI() // <Buffer 25 50 44 46 2d 31 2e

res.setHeader('Content-Type', 'application/pdf')
return res.end(data)

This opens a PDF in the browser as expected BUT when I click on the 'Download icon' on browser's PDF view enter image description here, it throws me an "Failed - Network error".

I already have the code which directly downloads the file as well (without viewing on browser):

res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Length', data.length)
res.setHeader('Content-Disposition', 'attachment; filename=name.Pdf')
return res.end(data)

This is not what I want.

What I'm looking for:

I am able to open in a browser or download individually without any problems. I need both to work together .ie. open the array buffer in the browser and then click the download icon on the browser view, that pdf content should get downloaded.

I use nunjucks as the view templating engine and I don't use any client side javascript.

Upvotes: 2

Views: 9580

Answers (1)

l2ysho
l2ysho

Reputation: 3053

Basically you need to specify content-length to do so. When downloading, browser compare content-length and real amount of data recieved, if it not match it is handled like malformed request

res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', 'attachment; filename=name.Pdf')
res.setHeader('Content-Length', data.length)
return res.end(data)

Edit

It is part of HTTP2 spec, look here

Upvotes: 4

Related Questions