You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Axios获取链接中的PDF并在Next.js API中返回给客户端?

在Next.js中通过Axios获取PDF并返回给客户端

1. 封装Axios函数获取PDF

先写一个可复用的Axios函数,专门用来获取远程PDF文件,注意设置正确的responseType避免二进制数据损坏:

import axios from 'axios';

export async function getRemotePdf(url) {
  try {
    const response = await axios.get(url, {
      responseType: 'arraybuffer', // 关键:指定响应类型为二进制数组
      headers: {
        'Accept': 'application/pdf'
      }
    });
    return response;
  } catch (error) {
    console.error('获取PDF失败:', error);
    throw error;
  }
}

2. Next.js中实现PDF下载接口

根据你使用的Next.js路由方案,选择对应的实现方式:

方案一:Pages Router(传统pages/api目录)

在pages/api/fileDownload.js(或.ts)中创建API路由:

import { getRemotePdf } from '../../utils/axios-pdf'; // 替换为你的函数实际路径

export default async function handler(req, res) {
  if (req.method !== 'GET') {
    res.status(405).json({ message: '仅支持GET请求' });
    return;
  }

  try {
    const pdfResponse = await getRemotePdf('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=test.pdf');
    
    // 返回PDF二进制数据
    res.send(pdfResponse.data);
  } catch (error) {
    res.status(500).json({ message: '下载PDF失败' });
  }
}

方案二:App Router(Next.js 13+ app/api目录)

在app/api/fileDownload/route.js(或.ts)中创建路由:

import { getRemotePdf } from '@/utils/axios-pdf'; // 替换为你的函数实际路径

export async function GET() {
  try {
    const pdfResponse = await getRemotePdf('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
    
    return new Response(pdfResponse.data, {
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename=test.pdf'
      }
    });
  } catch (error) {
    return new Response(JSON.stringify({ message: '下载PDF失败' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

3. 前端触发下载

在页面组件中通过链接或按钮调用接口:

// 页面组件示例
export default function DownloadPage() {
  return (
    <div>
      <a href="/api/fileDownload" download>下载PDF</a>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Masker234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:22:10