如何在ExtJS中通过带授权头的XHRRequest或Ajax展示从API获取的图片?
Solution for Loading Authenticated Images in PDF Generation via XHR/Ajax
Got it, let's tackle this problem head-on. The issue here is that when you reference image API URLs directly in XTemplate or HTML, the browser's automatic image request won't include the Authorization header—so we need to take control of the request using XHR or Fetch to inject your auth token, then render the image properly so your PDF generation tool can capture it.
Option 1: Using XMLHttpRequest (XHR)
This is the classic Ajax approach. We'll fetch the image as a Blob, convert it to an Object URL, and assign that to your image element:
function loadAuthenticatedImage(imageUrl, authToken, imgElement) { const xhr = new XMLHttpRequest(); xhr.open('GET', imageUrl, true); // Add your authorization token to the request header xhr.setRequestHeader('Authorization', `Bearer ${authToken}`); // Tell XHR to return the response as a Blob (binary image data) xhr.responseType = 'blob'; xhr.onload = function() { if (xhr.status === 200) { // Convert the Blob to a temporary Object URL const blobUrl = URL.createObjectURL(xhr.response); imgElement.src = blobUrl; // Clean up the Object URL once the image loads to avoid memory leaks imgElement.onload = function() { URL.revokeObjectURL(blobUrl); }; } else { console.error(`Failed to load image: ${xhr.statusText}`); // Fallback to a default error image if needed imgElement.src = '/path/to/default-error-image.png'; } }; xhr.onerror = function() { console.error('Network error occurred while loading image'); imgElement.src = '/path/to/default-error-image.png'; }; xhr.send(); }
Option 2: Using Fetch API (Modern Alternative)
If you prefer a cleaner, promise-based approach, Fetch works great too:
async function loadAuthenticatedImage(imageUrl, authToken, imgElement) { try { const response = await fetch(imageUrl, { headers: { 'Authorization': `Bearer ${authToken}` } }); if (!response.ok) { throw new Error(`Image request failed with status: ${response.status}`); } const blob = await response.blob(); const blobUrl = URL.createObjectURL(blob); imgElement.src = blobUrl; // Clean up the temporary URL after image load imgElement.onload = () => URL.revokeObjectURL(blobUrl); } catch (error) { console.error('Image load failed:', error); imgElement.src = '/path/to/default-error-image.png'; } }
How to Use This in Your XTemplate/HTML
- First, add an empty image element in your template (give it an ID or class to target):
<!-- Inside your XTemplate/HTML --> <img id="user-profile-image" alt="Authenticated Image">
- After your template renders, call the loading function with your token and image URL:
// Replace these with your actual values const authToken = 'your-valid-auth-token'; const imageApiUrl = 'https://your-api.com/images/123'; const imgElement = document.getElementById('user-profile-image'); // Use either the XHR or Fetch version loadAuthenticatedImage(imageApiUrl, authToken, imgElement);
Key Notes
- CORS Check: Make sure your image API allows cross-origin requests from the domain where your PDF generation tool runs, otherwise you'll get CORS errors.
- Memory Management: Always revoke the Object URL after the image loads to prevent memory leaks, especially if you're generating multiple PDFs.
- Template Timing: Ensure you run the image loading script after your XTemplate/HTML has finished rendering—otherwise, the
imgelement won't exist in the DOM yet.
内容的提问来源于stack exchange,提问作者AnthonyDa
相关产品推荐
相关产品推荐

