So we're having this problem. A user goes to upload a file, and if it's above 10MB, it just kind of times out the page, and clears, and no good error is thrown to describe what happened. Ideally, we would like to examine the file size when the user chooses the file they want to upload but I don't know if this is even possible. Our framework is built with ASP.NET, VB.NET, and Javascript (and ExtJS 3.0), and it r开发者_如何学JAVAuns in IE.
Anyway to do this?
I don't think there's any way to do this using standard HTML forms.
Take a look at SWFUpload. This will let you control the file size.
The code below works in Firefox and Chrome, but the check is omitted on IE and Opera. I think in IE you may need to use an ActiveXObject. Taken and modified slightly from here.
<script type="text/javascript">
var clicked = false;
function checkSize() {
var node = document.getElementById('file');
var check = node.files[0].fileSize;
if (check > 4096)
{
alert('Your file is too big!');
return false;
}
}
</script>
<form enctype="multipart/form-data" action="upload_file.php" method="post" class="body">
Select a file: <input type='file' id='file' name='file'>
<input type='submit' value=' Upload File ' onClick='return checkSize()'>
</form>
You can set the limit in web config, the property is called MaxRequestLength.
Set it in web.config, in the httpRuntime section :
<httpRuntime executionTimeout="90" maxRequestLength="4096" /> <-- number of bytes
That should be inserted under <system.web>
As for checking the size of the file, it's as easy as
If txtFileUpload.PostedFile.ContentLength > 1024 Then <-- bytes
Can you use or ave you tried using ActiveXObject?
Untested (probably won't work in IE7+)
function checkSize(fileInput, limit){
if(!window.ActiveXObject){
return false;
}
var oas = new ActiveXObject("Scripting.FileSystemObject"),
d = fileInput.value,
e = oas.getFile(d),
f = e.size;
return f <= limit; // in bytes
}
You can try swfupload, if Flash is an option for you.
With normal javascript and the HTML file tag it is impossible to do that, because of security reasons a page cannot access the user's disk which would be required to check the file size.
I've seen that being done with flash but I'm not a flash guy.
精彩评论