我给用户一个字段,他可以上传任何
图像文件我想检查文件不应该是
比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);
}
答案 0 :(得分:1)
在旧版浏览器中,上传之前无法获取文件大小,
解决方法是嵌入隐藏的flash(actionscript)
元素以获取文件大小
在最新的浏览器中,您可以使用HTML5 File API
来读取文件大小
检查基于HTML5 file API
的jquery filedrop插件(https://github.com/weixiyen/jquery-filedrop)
- NJ
答案 1 :(得分:0)
你应该使用这样的东西:
HttpPostedFile MyFile;
int FileLen;
System.IO.Stream MyStream;
MyFileCollection = Request.Files;
MyFile = MyFileCollection[0];
FileLen = MyFile.ContentLength;
FileLen是您文件的大小!将它与您想要的任何大小进行比较。 。
如果您想在客户端获取filezize,据我所知您可以使用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();" />