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.

2
  • I use similar setup and it always work, how do you handle it in FE? Commented Aug 23, 2020 at 18:03
  • @l2ysho - I use nunjucks as the view templating engine. I have no client side javascript. Commented Aug 23, 2020 at 18:07

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.