如何将API返回的Base64格式PDF文件从服务器保存到本地?
Got it, let's break this down—saving a Base64-encoded PDF from your API response is straightforward once you know the steps. Here's how to do it across common programming environments:
JavaScript (Browser Environment)
If you're building a web app and want users to download the PDF directly in their browser, you can create a dynamic download link:
// Assume this is your API response object const apiResponse = { Document: "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0a...", FileName: "file.pdf" }; // Step 1: Clean up the Base64 string (remove data URI prefix if present) const base64Data = apiResponse.Document.replace(/^data:application\/pdf;base64,/, ""); // Step 2: Decode Base64 to a Blob const byteChars = atob(base64Data); const byteNumbers = Array.from(byteChars, char => char.charCodeAt(0)); const byteArray = new Uint8Array(byteNumbers); const pdfBlob = new Blob([byteArray], { type: "application/pdf" }); // Step 3: Trigger the download const downloadUrl = URL.createObjectURL(pdfBlob); const link = document.createElement("a"); link.href = downloadUrl; link.download = apiResponse.FileName; document.body.appendChild(link); link.click(); // Clean up to avoid memory leaks document.body.removeChild(link); URL.revokeObjectURL(downloadUrl);
JavaScript (Node.js)
For server-side or CLI Node.js projects, use the built-in Buffer and fs modules:
const fs = require('fs').promises; // Your API response const apiResponse = { Document: "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0a...", FileName: "file.pdf" }; async function savePdf() { // Strip data URI prefix if needed const base64Data = apiResponse.Document.replace(/^data:application\/pdf;base64,/, ""); // Decode Base64 to buffer const pdfBuffer = Buffer.from(base64Data, 'base64'); // Write buffer to file await fs.writeFile(apiResponse.FileName, pdfBuffer); console.log(`PDF saved successfully as ${apiResponse.FileName}`); } savePdf().catch(err => console.error('Error saving PDF:', err));
Python
In Python, use the standard base64 module to decode and write binary data:
import base64 # Your API response api_response = { "Document": "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0a...", "FileName": "file.pdf" } # Strip any data URI prefix (split on comma and take the last part) base64_data = api_response["Document"].split(",")[-1] # Decode and save to file with open(api_response["FileName"], "wb") as pdf_file: pdf_file.write(base64.b64decode(base64_data)) print(f"PDF saved as {api_response['FileName']}")
Java
For Java applications, use java.util.Base64 and NIO file utilities:
import java.util.Base64; import java.nio.file.Files; import java.nio.file.Paths; public class SaveBase64Pdf { public static void main(String[] args) { // Simulated API response data String documentBase64 = "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0a..."; String fileName = "file.pdf"; // Remove data URI prefix if present String cleanBase64 = documentBase64.replaceFirst("^data:application/pdf;base64,", ""); try { // Decode Base64 to byte array byte[] pdfBytes = Base64.getDecoder().decode(cleanBase64); // Write byte array to file Files.write(Paths.get(fileName), pdfBytes); System.out.println("PDF saved successfully!"); } catch (Exception e) { e.printStackTrace(); } } }
Quick Tip
Always double-check if your Base64 string includes a data URI prefix (like data:application/pdf;base64,). Most decoding libraries will fail if you leave this prefix intact, so stripping it first is crucial.
内容的提问来源于stack exchange,提问作者Shaxrillo

