2

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.

Nikhil Nanjappa
  • 6,454
  • 3
  • 28
  • 44

1 Answers1

3

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

l2ysho
  • 2,542
  • 1
  • 20
  • 41
  • i've already tried this ... `'Content-Disposition', 'attachment;` would directly download the file without opening it in the browser which is not what I want. – Nikhil Nanjappa Aug 23 '20 at 18:14
  • How about dynamically set content-disposition header to attachement for download and inline for view? you can make condition by query parameter => `/myfile.pdf?download=true` – l2ysho Aug 23 '20 at 18:20
  • I am able to do them individually without any problems (view and download separately). But what I want is - on click of a single say link, open a pdf and then when I click on the download **of the browser** (the icon shown in the question as an image), it downloads. – Nikhil Nanjappa Aug 23 '20 at 18:25