javascript - 如何在 IE8 html4 中检查文件大小

标签 javascript jquery css internet-explorer-8

我使用 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 有什么好的解决方案吗???

最佳答案

我知道我参加聚会迟到了,但我实际上可以回答这个问题!

这里有三个选项:

  1. 使用ActiveX检查文件大小(取决于用户浏览器) 设置,这可能不起作用,或者可能会提示他们允许 要运行的 ActiveX 对象)
  2. 检查服务器端的文件大小,然后 文件太大时处理
  3. 限制请求大小,以便在文件太大时发生错误(您将再次需要处理此错误)

解决方案 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/

相关文章:

更改选项卡时 JavaScript 在 iPad 上暂停 : is there a way to know when coming back?

javascript - jquery: fadeOut().empty().append(...).fadeIn() 只有第一次不能正常工作

javascript - 是否可以将 d3.js 与 gatsby.js 框架一起使用?

javascript - 在 $.ajax 中获取字符串响应

javascript - 使用 JQuery 或 Javascript 选择 Google map 的下拉菜单更改纬度

javascript - 使用 jQuery 或 CSS 将 100% 宽度的图像调整为垂直居中?

jquery - 移动切换效果

javascript - 如何去除背景图像周围的灰色边框?

php - jQuery POST 多维表单数组

javascript - 如何在 Extjs 4.0 中突出显示鼠标悬停时的网格?