簡體   English   中英

檢查上傳文件的大小(以 mb 為單位)

[英]Check size of uploaded file in mb

我需要驗證用戶上傳的文件不超過 10mb。 這會完成工作嗎?

var fileSize = imageFile.ContentLength;
if ((fileSize * 131072) > 10)
{
    // image is too large
}

我一直在看這個線程,而這一次......但也讓我有所有的方式。 我用這個作為轉換率。

.ContentLength獲取以字節為單位的大小。 然后我需要將它轉換為mb。

由於您以字節為單位給出大小,因此您需要除以1048576 (即1024 * 1024 ):

var fileSize = imageFile.ContentLength;
if ((fileSize / 1048576.0) > 10)
{
    // image is too large
}

但是如果您預先計算 10mb 中的字節數,則計算會更容易閱讀:

private const int TenMegaBytes = 10 * 1024 * 1024;


var fileSize = imageFile.ContentLength;
if ((fileSize > TenMegaBytes)
{
    // image is too large
}

您可以使用此方法將獲得的bytes轉換為 MB:

static double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
}

倍數字節 (B) 的前綴:
1024 字節 = 1 千字節
1024 KB = 1 兆字節

double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
} 

var fileSize = imageFile.ContentLength;

if (ConvertBytesToMegabytes(fileSize ) > 10f)
{
    // image is too large
}
var fileSize = file.ContentLength;
if (fileSize > 10 * 1024 * 1024)
{
    // Do whatever..
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM