js实现微信下载PDF

js实现微信下载PDF

五月 31, 2023 评论 10 阅读 514 点赞 0 收藏 0
<!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>
  <h1>
    <p onclick="downloadPdf1()">点击这里</p>
  </h1>
  <script>

    async function downloadPdf1() {
      const fileUrl = 'http://192.168.15.183:3000/file.pdf';
      const fileName = 'file.pdf';

      try {
        const response = await axios.get(fileUrl, {
          responseType: 'blob',
          headers: {
            'User-Agent': navigator.userAgent,
          },
        });

        const blob = new Blob([response.data], { type: 'application/pdf' });

        // 创建一个临时的下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = fileName;

        // 触发下载
        downloadLink.click();

        // 清理临时链接
        URL.revokeObjectURL(downloadLink.href);
      } catch (error) {
        console.error(error);
        // 处理错误
      }
    }

  </script>
</body>

</html>
*
*
*