您的问题是因为 10 之前的所有 IE 版本都不支持 HTML5 File API。因此,考虑到 this 是您的 HTMLInputElement,以下内容将不起作用:
this.files[0].size;
原因是 HTMLInputElement.FileList 不存在,因为缺少文件 API 支持,但是您可以使用 HTMLInputElement.value 获取文件名。但这不是你想要的。您想获取文件的大小。再一次,由于缺少 File API 支持,IE
第一个解决方案(客户端 - jQuery)
你提议:
我可以使用浏览器检测说“嘿,如果 IE 执行 activeX,则执行 jQuery”
如果你想这样做,你可以有类似的东西:
$(function(){
$('#File1').bind('change', function() {
var maxFileSize = 1024000; // 1MB -> 1000 * 1024
var fileSize;
// If current browser is IE < 10, use ActiveX
if (isIE() && isIE() < 10) {
var filePath = this.value;
if (filePath != '') {
var AxFSObj = new ActiveXObject("Scripting.FileSystemObject");
var AxFSObjFile = AxFSObj.getFile(filePath);
fileSize = AxFSObjFile.size;
}
} else {
// IE >= 10 or not IE
if (this.value != '') {
fileSize = this.files[0].size;
}
}
if (fileSize < maxFileSize) {
// Enable submit button and remove any error message
$('#button_fileUpload').prop('disabled', false);
$('#lbl_uploadMessage').text('');
} else {
// Disable submit button and show error message
$('#button_fileUpload').prop('disabled', true);
$('#lbl_uploadMessage').text('File too big !');
}
});
});
// Check if the browser is Internet Explorer
function isIE() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
警告!
在盲目复制此代码之前,请注意 ActiveX 解决方案确实很差。要使其工作,用户必须更改其Internet Options。此外,此解决方案不适用于公共站点,仅适用于 Intranet 应用程序。
但我想知道是否有比 ActiveX 更可靠的方法?
不,IE没有
第二种解决方案(jQuery插件)
您可以使用jQuery File Upload。你可以很容易地得到它的大小。
第三种解决方案(服务器端 - VB.NET)
考虑到您有这些 asp 控件:
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" ForeColor="Red" />
一旦与服务器端进行交互,您就可以检查选择的文件大小。例如,在这里,一旦用户单击上传按钮,我就会检查文件的大小。
Protected Sub btnFileUpload_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button_fileUpload.Click
' A temporary folder
Dim savePath As String = "c:\temp\uploads\"
If (fileUpload.HasFile) Then
Dim fileSize As Integer = fileUpload.PostedFile.ContentLength
' 1MB -> 1000 * 1024
If (fileSize < 1024000) Then
savePath += Server.HtmlEncode(fileUpload.FileName)
fileUpload.SaveAs(savePath)
lbl_uploadMessage.Text = "Your file was uploaded successfully."
Else
lbl_uploadMessage.Text = "Your file was not uploaded because " +
"it exceeds the 1 MB size limit."
End If
Else
lbl_uploadMessage.Text = "You did not specify a file to upload."
End If
End Sub
编辑
正如您所说,最后一个解决方案不适用于太大的文件。要使此解决方案起作用,您必须增加 web.config 文件中的最大上传文件大小:
<configuration>
<system.web>
<httpRuntime maxRequestLength="52428800" /> <!--50MB-->
</system.web>
</configuration>