我需要验证用户上传的文件不超过 10mb。这会完成工作吗?
var fileSize = imageFile.ContentLength;
if ((fileSize * 131072) > 10)
{
// image is too large
}
我一直在看this thread , 和 this one ......但都没有让我一路走到那里。我正在使用 this作为转化率。
.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
}
关于c# - 检查上传文件的大小(以 mb 为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43617227/