如何在 C# 中上传之前知道确切的文件大小

本文关键字:文件大小 | 更新日期: 2023-09-27 18:33:33

>我给用户一个字段,他可以在其中上传任何
图像文件 我想检查该文件是否不应该
比 350kb 更大....如何在 C# 中执行此操作

                HttpPostedFileBase file = Request.Files[0];
                string mynewpath = Request.PhysicalApplicationPath + "Upload''";
                if (file.ContentLength > 0)
                {
                    // here i want to check that if file size is more then 350kb then i will give error 
                    string[] extarray = new string[] { "image/jpeg", "image/jpg","image/png", "image/gif" };
                    var isallowedfile = extarray.Contains(file.ContentType);
                    if (!isallowedfile)
                    {
                        ModelState.AddModelError("", "Only image files (.jpeg , .gif , .png ) are accepted, please browse a image file");
                        return View("SurveyOptions", model);
                    }
                    string filename = Guid.NewGuid() + Path.GetFileName(file.FileName);
                    file.SaveAs(mynewpath + filename);
                }

如何在 C# 中上传之前知道确切的文件大小

  1. 在较旧的浏览器中,无法在上传之前获取文件大小,解决方法是嵌入隐藏的flash(actionscript)元素以获取文件大小

  2. 在最新的浏览器中,您可以使用HTML5 File API读取文件大小

检查基于HTML5 file API的jQuery文件删除插件(https://github.com/weixiyen/jquery-filedrop

--新泽西州

你应该使用这样的东西:

HttpPostedFile MyFile;
int FileLen;
System.IO.Stream MyStream;
MyFileCollection = Request.Files;
MyFile = MyFileCollection[0];
FileLen = MyFile.ContentLength;

FileLen 是你的文件的大小!将其与您想要的任何大小进行比较。 .

.

如果你想在客户端获取文件zize,据我所知,你可以使用html文件上传器来做到这一点:

function validateFile()
{
var strFileName = document.form1.file1.value;
var strExtName = strFileName.substring(strFileName.lastIndexOf('.')).toLowerCase();
alert(strFileName);
alert(strExtName);
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var e = objFSO.getFile(strFileName);
var fileSize = e.size;
//file size limit for 10mb
if (fileSize > 10485760){
alert("maximum size of uploaded file should be less than 10 MB.");
return false; 
}
else
return true;
}

<input type ="file" id="file1" name="file1" contentEditable="false" onchange="validateFile();" />