如何从 url 获取远程 PDF 并使用 Express js 发送到客户端?

发布于 2025-01-14 16:03:11 字数 94 浏览 1 评论 0原文

我想从 URL 获取 pdf 并通过 REST 端点将其发送到 Express (JS) 应用程序中的客户端。但是,大多数资源都集中于发送位于本地文件系统上的 PDF 文件。

I would like to fetch a pdf from a URL and send it to the client in an Express (JS) application via a REST endpoint. However, most resources are focused on sending a PDF file located on the local file system.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天邊彩虹 2025-01-21 16:03:11

这是一个效果很好的简单示例。

const axios = require('axios');
const express = require('express');

const app = express();

const url = 'https://example.com/file';
const fileName = 'pdf-file';

app.get('/', async (req, res) => {
  const stream = await axios.get(url, { responseType: 'stream' });
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `inline; filename=${fileName}.pdf`);
  return stream.data.pipe(res);
});

app.listen(3000);

Here is a simple example that works great.

const axios = require('axios');
const express = require('express');

const app = express();

const url = 'https://example.com/file';
const fileName = 'pdf-file';

app.get('/', async (req, res) => {
  const stream = await axios.get(url, { responseType: 'stream' });
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `inline; filename=${fileName}.pdf`);
  return stream.data.pipe(res);
});

app.listen(3000);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文