fromMediaItem static method
Creates an AttachedFile from a MediaItem.
If the MediaItem was created using MediaItem.fromNetwork and doesn't have bytes yet, this method will fetch the file from the network URL.
Example:
final mediaItem = MediaItem.fromNetwork('https://example.com/image.png');
final attachedFile = await AttachedFile.fromMediaItem(mediaItem);
Implementation
static Future<AttachedFile> fromMediaItem(MediaItem mediaItem) async {
// If bytes are already present (e.g., from MediaItem.fromFile), use them directly
if (mediaItem.bytes != null) {
return AttachedFile._(mediaItem);
}
// If no bytes, fetch from the network URL
final uri = Uri.parse(mediaItem.url);
final response = await http.get(uri);
// Extract filename from the URL or use a default
final name =
uri.pathSegments.isNotEmpty ? uri.pathSegments.last : 'file.txt';
// Create a new MediaItem with the fetched bytes and attachment:// URL
final media = MediaItem.fromNetwork(
'attachment://$name',
spoiler: mediaItem.spoiler,
proxyUrl: mediaItem.proxyUrl,
height: mediaItem.height,
width: mediaItem.width,
contentType: mediaItem.contentType,
description: mediaItem.description,
)..bytes = response.bodyBytes;
return AttachedFile._(media);
}