Expo中如何携带JWT令牌下载PDF文件?
携带JWT令牌实现PDF发票下载(含expo-file-dl配置)
通用实现思路
所有需认证的下载请求,核心都是在请求头中加入Authorization字段,格式统一为 Bearer <你的JWT令牌>。后端接口需提前实现该头的验证逻辑,验证通过后再返回PDF文件。
原生Fetch示例
如果不用第三方库,直接用Fetch API即可完成:
async function downloadInvoiceWithJWT(token) { const response = await fetch('https://your-api-url/invoice/download', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/pdf' // 明确告知服务器期望返回PDF格式 } }); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } const blob = await response.blob(); // 后续可将blob保存到本地或通过Expo的文件系统API打开 }
expo-file-dl 具体配置
expo-file-dl 的 downloadAsync 方法支持通过 options 参数传入自定义请求头,直接添加Authorization即可,示例如下:
import * as FileDownload from 'expo-file-dl'; import * as FileSystem from 'expo-file-system'; async function downloadInvoice(token) { try { const downloadUri = 'https://your-api-url/invoice/download'; const savePath = `${FileSystem.documentDirectory}invoice_${Date.now()}.pdf`; // 生成唯一文件名 const result = await FileDownload.downloadAsync(downloadUri, savePath, { headers: { 'Authorization': `Bearer ${token}` }, // 可选配置:设置下载进度回调 onProgress: (progress) => { console.log(`下载进度:${(progress.totalBytesWritten / progress.totalBytesExpectedToWrite * 100).toFixed(2)}%`); } }); console.log('下载完成,文件路径:', result.uri); // 调用系统打开文件 await FileSystem.openAsync(result.uri); } catch (error) { console.error('下载失败:', error.message); } }
注意事项
- 确保后端接口正确校验
Authorization头,验证失败时返回401等状态码,前端需捕获并处理(比如引导用户重新登录) - 若JWT令牌有过期时间,建议在请求前先检查令牌有效性,避免无效请求
- 大文件下载时,
expo-file-dl会自动处理断点续传,无需额外配置
内容的提问来源于stack exchange,提问作者DarkSide77
相关产品推荐
相关产品推荐

