user2158720
user2158720

Reputation: 45

Send pdf via express to js client and download

I am trying to send pdf file from my express server using the client when requested like this:

  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=test.pdf');
  fs.createReadStream('test.pdf').pipe(res);

And then on the client side I am trying to download it by taking the resulting string converting it to a url and downloading from there.

var blob = new Blob[pdfString], { type: 'application/pdf' });
var url = window.URL;
var downloadUrl = url.createObjectURL(blob);

However the resulting file is two empty pages and I beleive think it might be because the resulting file is url is to large? If anyone could figure out whats wrong here or tell me of a better way to do it that would be awesome.

Upvotes: 1

Views: 878

Answers (1)

user2158720
user2158720

Reputation: 45

I was able to figure it out using XMlHttpRequest:

   var req = new XMLHttpRequest();
      req.open('GET', path , true);
      req.responseType = "arraybuffer";
      req.onload = (event) => {
        downloadPdf(req.response); //This is where I convert to blob
      }
      req.send();

Upvotes: 1

Related Questions