node实现微信下载PDF

node实现微信下载PDF

五月 31, 2023 评论 10 阅读 511 点赞 0 收藏 0
const request = require('request')
const fs = require('fs');

module.exports = {
  //测试 api 服务器能否正常被请求
  testAPI: (req, res) => {
    // 如果获取数据成功,则直接返回成功的数据结果
    res.send({
      status: 200,
      message: 'ok',
      data: '请求后台api成功'
    })
  },
  // 文章接口
  download: async (req, res) => {
    const fileUrl = 'http://192.168.15.183:3000/file.pdf';
    const userAgent = req.headers['user-agent'] || '';
    const fileName = 'file.pdf';
    await request({
          url: fileUrl,
          method: 'GET',
          encoding: null,
          headers: {
          'User-Agent': userAgent,
          },
            }, async (err, response, body) => {
              if (err) {
                console.error(err);
                res.status(500).send('服务器错误');
              } else {
                // 将文件保存到本地
                   await fs.writeFileSync(fileName, body, 'binary');
                    // 返回下载文件
                    await res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
                    await  res.setHeader('Content-Type', 'application/pdf');
                    await  res.send(body);
              }
            });
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微信内置浏览器文件下载</title>
</head>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>

<body>
  <p><a href="/test">测试</a></p>
  <p>请点击下面的链接下载 PDF 文件:</p>
  <p><a href="/download">点击这里</a></p>
</body>

</html>
*
*
*