@@ -224,28 +224,49 @@ export class MedplumAttachmentFile implements AttachmentFile {
224224 *
225225 * Works with Binary resources that have either:
226226 * - Inline data (base64 encoded)
227- * - A presigned URL to download from
227+ * - External storage (downloaded via Medplum client)
228228 */
229229 async read ( ) : Promise < Buffer > {
230- const binary = await this . medplum . readResource ( 'Binary' , this . binaryId ) ;
230+ try {
231+ // Use Medplum's download method which handles both inline and external storage
232+ const data = await this . medplum . download ( `Binary/${ this . binaryId } ` ) ;
233+
234+ // Convert to Buffer
235+ if ( data instanceof ArrayBuffer ) {
236+ return Buffer . from ( data ) ;
237+ } else if ( data instanceof Blob ) {
238+ const arrayBuffer = await data . arrayBuffer ( ) ;
239+ return Buffer . from ( arrayBuffer ) ;
240+ } else if ( typeof data === 'string' ) {
241+ // If it's a base64 string
242+ return Buffer . from ( data , 'base64' ) ;
243+ } else if ( Buffer . isBuffer ( data ) ) {
244+ return data ;
245+ }
231246
232- // If data is embedded in the Binary resource, use it directly
233- if ( binary . data ) {
234- return Buffer . from ( binary . data , 'base64' ) ;
235- }
247+ throw new Error ( `Unexpected data type from Medplum download: ${ typeof data } ` ) ;
248+ } catch ( error ) {
249+ // Fallback to reading the Binary resource directly if download fails
250+ const binary = await this . medplum . readResource ( 'Binary' , this . binaryId ) ;
236251
237- // If data is not embedded but a URL is available, download it
238- if ( binary . url ) {
239- const response = await fetch ( binary . url ) ;
240- if ( ! response . ok ) {
241- throw new Error ( `Failed to download binary from URL: ${ response . statusText } ` ) ;
252+ // If data is embedded in the Binary resource, use it directly
253+ if ( binary . data ) {
254+ return Buffer . from ( binary . data , 'base64' ) ;
242255 }
243- const arrayBuffer = await response . arrayBuffer ( ) ;
244- return Buffer . from ( arrayBuffer ) ;
245- }
246256
247- // Neither data nor URL available
248- throw new Error ( 'Binary resource has neither data nor url' ) ;
257+ // If data is not embedded but a URL is available, download it
258+ if ( binary . url ) {
259+ const response = await fetch ( binary . url ) ;
260+ if ( ! response . ok ) {
261+ throw new Error ( `Failed to download binary from URL: ${ response . statusText } ` ) ;
262+ }
263+ const arrayBuffer = await response . arrayBuffer ( ) ;
264+ return Buffer . from ( arrayBuffer ) ;
265+ }
266+
267+ // Re-throw original error if fallback also fails
268+ throw error ;
269+ }
249270 }
250271
251272 /**
0 commit comments