-4

我给用户一个字段,他可以上传任何
图像文件我想检查文件不
应该大于 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);
                }
4

2 回答 2

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

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

检查基于 jquery filedrop 插件(https://github.com/weixiyen/jquery-filedropHTML5 file API

--新泽西州

于 2012-05-09T12:29:07.313 回答
0

你应该使用这样的东西:

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

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

如果你想在客户端获取文件,据我所知,你可以使用 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();" />
于 2012-05-09T12:21:50.160 回答