[英]Check size of uploaded file in mb
I need to verify that a file upload by a user does not exceed 10mb.我需要验证用户上传的文件不超过 10mb。 Will this get the job done?
这会完成工作吗?
var fileSize = imageFile.ContentLength;
if ((fileSize * 131072) > 10)
{
// image is too large
}
I've been looking at this thread , and this one ... but neither gets me all the way there.我一直在看这个线程,而这一次......但也让我有所有的方式。 I'm using this as the conversion ratio.
我用这个作为转换率。
.ContentLength
gets the size in bytes. .ContentLength
获取以字节为单位的大小。 Then I need to convert it to mb.然后我需要将它转换为mb。
Since you are given the size in bytes, you need to divide by 1048576
(ie 1024 * 1024
):由于您以字节为单位给出大小,因此您需要除以
1048576
(即1024 * 1024
):
var fileSize = imageFile.ContentLength;
if ((fileSize / 1048576.0) > 10)
{
// image is too large
}
But the calculation is a bit easier to read if you pre-calculate the number of bytes in 10mb:但是如果您预先计算 10mb 中的字节数,则计算会更容易阅读:
private const int TenMegaBytes = 10 * 1024 * 1024;
var fileSize = imageFile.ContentLength;
if ((fileSize > TenMegaBytes)
{
// image is too large
}
You can use this method to convert the bytes
you got to MB:您可以使用此方法将获得的
bytes
转换为 MB:
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
Prefixes for multiples of bytes (B):倍数字节 (B) 的前缀:
1024 bytes = 1kilobyte 1024 字节 = 1 千字节
1024 kilobyte = 1megabyte 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.