React中如何直接下载API返回的原始格式PDF文件?
Let's break down why your current approach isn't working and get that PDF downloading correctly. The core issue is that your API is returning raw PDF content as a text string, and the fileDownload method you're using isn't properly converting that string into a valid binary PDF file. Here are a few reliable solutions:
1. Configure Your Request to Get a Blob Directly
The best fix is to tell your HTTP client to fetch the response as a Blob (binary large object) instead of a string. This preserves the PDF's binary structure right from the start.
Example with Axios:
import axios from 'axios'; const downloadCustomerPDF = async (customerId) => { try { const response = await axios.get('/your-api-path', { responseType: 'blob', // Critical: This tells Axios to return a Blob params: { customer_id: customerId } }); // Create a download link for the Blob const url = window.URL.createObjectURL(response.data); const link = document.createElement('a'); link.href = url; link.download = `customer-${customerId}.pdf`; document.body.appendChild(link); link.click(); // Clean up to avoid memory leaks document.body.removeChild(link); window.URL.revokeObjectURL(url); } catch (err) { console.error('Error downloading PDF:', err); } };
Example with Fetch API:
const downloadCustomerPDF = (customerId) => { fetch(`/your-api-path?customer_id=${customerId}`, { method: 'GET', // Add any required headers here }) .then(res => res.blob()) // Convert response to Blob .then(blob => { const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `customer-${customerId}.pdf`; document.body.appendChild(link); link.click(); // Cleanup document.body.removeChild(link); window.URL.revokeObjectURL(url); }) .catch(err => console.error('Error downloading PDF:', err)); };
2. Convert the Raw PDF String to a Blob (If You Can't Modify the Request)
If you're stuck with the API returning a text string (like the sample you shared), you need to convert that string back into a binary format before downloading. Here's how:
const convertPDFStringToBlob = (pdfString) => { // Encode the string into a Uint8Array (binary data) const uint8Array = new TextEncoder().encode(pdfString); // Create a Blob with the correct MIME type for PDF return new Blob([uint8Array], { type: 'application/pdf' }); }; // Usage with your existing API response: const pdfBlob = convertPDFStringToBlob(apiCall.data); const url = window.URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = `customer-${payload.customer_id}.pdf`; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url);
Why Your Original Method Failed
Most basic fileDownload functions treat input strings as plain text. Since PDF is a binary format, saving it as text corrupts its internal structure (like the compressed stream data in your sample), making it unreadable by PDF viewers. Converting to a Blob ensures the file is saved with the correct binary encoding.
Quick Check
Make sure your API's response header includes Content-Type: application/pdf—this helps browsers recognize the file type correctly, even if you're handling the download manually.
内容的提问来源于stack exchange,提问作者Deep Shah

