如何在Umbraco中获取上传字段@item.GetPropertyValue("uploadPDF")的KB/MB大小值
Got it, let's break down how to get the formatted file size (KB/MB) for your uploadPDF field in Umbraco. Here's a straightforward approach that works for most recent Umbraco versions (8+), plus a note for older versions:
Step 1: Retrieve the media item linked to your upload field
Umbraco's Upload property type stores a reference to a media node in your media library. First, we need to fetch that media node from the property:
@{ // Get the media item associated with the uploadPDF field var pdfMedia = item.GetPropertyValue<IPublishedContent>("uploadPDF"); }
Step 2: Extract the raw file size in bytes
Every media item in Umbraco has a built-in property umbracoBytes that stores the file size in bytes. We'll pull that value next:
if (pdfMedia != null) { // Get the file size in bytes (umbracoBytes is a default media property) var fileSizeBytes = pdfMedia.GetPropertyValue<int>("umbracoBytes"); }
Step 3: Convert bytes to KB/MB for readability
Now we'll format the raw byte value into a user-friendly string (KB or MB, with rounding for clarity):
string formattedFileSize; if (fileSizeBytes >= 1024 * 1024) { // Convert to MB, round to 2 decimal places formattedFileSize = $"{Math.Round(fileSizeBytes / (1024.0 * 1024.0), 2)} MB"; } else if (fileSizeBytes >= 1024) { // Convert to KB, round to 2 decimal places formattedFileSize = $"{Math.Round(fileSizeBytes / 1024.0, 2)} KB"; } else { // Fallback to bytes for tiny files formattedFileSize = $"{fileSizeBytes} Bytes"; } // Output the result <p>PDF File Size: @formattedFileSize</p>
Full Working Code
Putting it all together with null checks to avoid errors if no file is uploaded:
@{ var pdfMedia = item.GetPropertyValue<IPublishedContent>("uploadPDF"); if (pdfMedia != null) { var fileSizeBytes = pdfMedia.GetPropertyValue<int>("umbracoBytes"); string formattedFileSize; if (fileSizeBytes >= 1024 * 1024) { formattedFileSize = $"{Math.Round(fileSizeBytes / (1024.0 * 1024.0), 2)} MB"; } else if (fileSizeBytes >= 1024) { formattedFileSize = $"{Math.Round(fileSizeBytes / 1024.0, 2)} KB"; } else { formattedFileSize = $"{fileSizeBytes} Bytes"; } <p>PDF File Size: @formattedFileSize</p> } else { <p>No PDF file uploaded.</p> } }
Note for Umbraco 7 Users
If you're on Umbraco 7, the Upload property returns a string (the media ID) instead of directly returning IPublishedContent. You'll need to use Umbraco.TypedMedia() to fetch the media item:
@{ var pdfMediaId = item.GetPropertyValue<string>("uploadPDF"); var pdfMedia = Umbraco.TypedMedia(pdfMediaId); // Rest of the logic remains the same as above }
Quick Tips
- Always include null checks to handle cases where no file has been uploaded.
- The
umbracoBytesproperty is a default field for all media items, so it should exist for any file uploaded to the media library. - Adjust the rounding (e.g.,
Math.Round(..., 1)for 1 decimal place) if you prefer a different formatting style.
内容的提问来源于stack exchange,提问作者Paul Gwamanda

