Angular中如何将bytea转换为可下载PDF文件?
Hey there! Let's get that bytea data converted into a working downloadable PDF. The problem with your current code is that bytea (usually from PostgreSQL) gets sent as an encoded string (either Base64 or hexadecimal) from the backend, not raw binary data. Shoving that string directly into a Blob will create a corrupted file—here's how to fix it:
First, Identify Your bytea Format
Check what obj.content actually is by logging typeof obj.content and the value itself. It's likely one of two formats:
Case 1: Base64 Encoded String
If your data looks like data:application/pdf;base64,JVBERi0xLjMK... or just the raw Base64 string, use this code to decode it properly:
downloadFile(instanceId){ this.filestorageService.loadByInstance(instanceId).subscribe( obj => { let data = obj.content; // Strip off the data URI prefix if present if (data.startsWith('data:')) { data = data.split(',')[1]; } // Decode Base64 to raw binary const byteChars = atob(data); const byteNumbers = Array.from(byteChars, char => char.charCodeAt(0)); const byteArray = new Uint8Array(byteNumbers); // Create Blob and trigger download const blob = new Blob([byteArray], { type: 'application/pdf' }); const url = window.URL.createObjectURL(blob); // Use an anchor tag to avoid popup blockers const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = 'document.pdf'; // Customize your filename here document.body.appendChild(downloadLink); downloadLink.click(); // Clean up window.URL.revokeObjectURL(url); document.body.removeChild(downloadLink); }); }
Case 2: Hexadecimal String
If your data starts with \x (like \x255044462D312E36...) or is just a raw hex string, convert it to binary with this approach:
downloadFile(instanceId){ this.filestorageService.loadByInstance(instanceId).subscribe( obj => { let data = obj.content; // Remove the \x prefix if present if (data.startsWith('\\x')) { data = data.slice(2); } // Convert hex string to Uint8Array const byteArray = new Uint8Array( data.match(/.{1,2}/g).map(hexPair => parseInt(hexPair, 16)) ); // Create Blob and trigger download const blob = new Blob([byteArray], { type: 'application/pdf' }); const url = window.URL.createObjectURL(blob); const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = 'document.pdf'; document.body.appendChild(downloadLink); downloadLink.click(); window.URL.revokeObjectURL(url); document.body.removeChild(downloadLink); }); }
Why Your Original Code Failed
When you pass the encoded string directly to Blob([data]), it treats each character in the string as a separate byte—this mangles the binary structure of the PDF, making it unreadable. By decoding the string to a Uint8Array first, you're restoring the original binary data the PDF needs.
内容的提问来源于stack exchange,提问作者FlyingTurtle

