我使用 FileReader 来检查输入文件大小。
但是我可爱的客户想要 IE8,所以我需要一种方法来检查这里的文件大小。
IE8不支持FileReader和其他东西。
这就是我为 html5 所做的
输入
<input accept="image/png,image/gif,image/jpeg" id="user_profile_photo" name="user_profile[photo]" type="file">
javasciprt
$("#user_profile_photo").change(function(){
imageIsDelete = false;
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
if(imageSizeValidationCheck(input.files[0].size)){
$('#myprofile_image').attr('src', e.target.result);
}
}
reader.readAsDataURL(input.files[0]);
}
}
function imageSizeValidationCheck(size){
if(size/1024>200){
alert("Please upload image size lower then 200KB");
$("#user_profile_photo").replaceWith($("#user_profile_photo").clone( true ) );
return false;
}else{
return true;
}
}
针对 html4 和 IE8 有什么好的解决方案吗???
最佳答案
我知道我参加聚会迟到了,但我实际上可以回答这个问题!
这里有三个选项:
- 使用ActiveX检查文件大小(取决于用户浏览器) 设置,这可能不起作用,或者可能会提示他们允许 要运行的 ActiveX 对象)
- 检查服务器端的文件大小,然后 文件太大时处理
- 限制请求大小,以便在文件太大时发生错误(您将再次需要处理此错误)
解决方案 1(这将同时处理 HTML5 兼容浏览器和旧版浏览器):
// Get the file size
var size;
var maxSize = 200;
if (window.FileReader && window.File && window.FileList && window.Blob) {
// HTML5 File API Supported
size = $('#user_profile_photo')[0].files[0].size;
}
else {
// Need to use ActiveX to read the file size
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = $('#user_profile_photo').val();
var thefile = myFSO.getFile(filepath);
size = thefile.size;
}
if (size > (maxSize * 1024)) {
alert('The selected file is bigger than the maximum allowed file size.\r\n\r\nSelected file size: ' + Math.round((size / 1024) * 100) / 100 + 'KB\r\nMax allowed file size: ' + maxSize + 'KB');
return false;
}
解决方案 2:这取决于您的服务器端代码语言是什么,但它只是围绕检查 HttpPostedFileBase 的大小或提供的字节数组的长度,然后返回到页面并向用户显示一条消息。
解决方案 3 - 将以下内容添加到您的 web.config(假设您使用的是 asp.net):
<system.web>
<httpRuntime maxRequestLength="10240" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="10485760" />
</requestFiltering>
</security>
</system.webServer>
然后,您将需要进行一些错误处理来发现此错误(同样,根据您的服务器端技术,它可能会有所不同)。
希望这对某人有帮助(我想 3 年后 OP 不会仍然停留在这个问题上!)。
关于javascript - 如何在 IE8 html4 中检查文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20838469/