以mb为单位检查上传文件的大小

Cas*_*ton 2 c#

我需要验证用户上传的文件不超过10mb.这会完成工作吗?

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

我一直在看这个帖子,而这一个 ...但是它们都没有让我一路走来.我用作为转换率.

.ContentLength得到大小的字节.然后我需要将其转换为mb.

Dav*_*idG 17

既然你给出的字节大小,你需要划分1048576(即1024 * 1024):

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

但是,如果预先计算10mb中的字节数,计算会更容易阅读:

private const int TenMegaBytes = 10 * 1024 * 1024;


var fileSize = imageFile.ContentLength;
if ((fileSize > TenMegaBytes)
{
    // image is too large
}
Run Code Online (Sandbox Code Playgroud)