Send pdf via express to js client and download

 ̄綄美尐妖づ 提交于 2021-01-28 12:20:12

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/48285771/send-pdf-via-express-to-js-client-and-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!