在使用JavaScript上传文件之前,有什么方法可以检查文件大小?


当前回答

如果你正在使用jQuery验证,你可以这样写:

$.validator.addMethod(
  "maxfilesize",
  function (value, element) {
    if (this.optional(element) || ! element.files || ! element.files[0]) {
      return true;
    } else {
      return element.files[0].size <= 1024 * 1024 * 2;
    }
  },
  'The file size can not exceed 2MiB.'
);

其他回答

简单的方法是

const myFile = document.getElementById("fileUpload").files[0]; 
            if (myFIle.size > 2097152) // 2 MiB for bytes.
            {
                alert("File size must under 2MiB!");
                return;
            }

你可以试试这个fineuploader

它在IE6(及以上版本)、Chrome或Firefox下运行良好

我偶然遇到了这个问题,我需要的一行代码隐藏在大块的代码中。

简单回答:this.files[0].size

顺便说一下,不需要JQuery。

是的,您可以为此使用文件API。

这是一个完整的例子(见评论):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() { // (Can't use `typeof FileReader === "function"` because apparently it // comes back as "object" on some browsers. So just see if it's there // at all.) if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal console.log("The file API isn't supported on this browser yet."); return; } var input = document.getElementById('fileinput'); if (!input.files) { // This is VERY unlikely, browser support is near-universal console.error("This browser doesn't seem to support the `files` property of file inputs."); } else if (!input.files[0]) { addPara("Please select a file before clicking 'Load'"); } else { var file = input.files[0]; addPara("File " + file.name + " is " + file.size + " bytes in size"); } }); function addPara(text) { var p = document.createElement("p"); p.textContent = text; document.body.appendChild(p); } body { font-family: sans-serif; } <form action='#' onsubmit="return false;"> <input type='file' id='fileinput'> <input type='button' id='btnLoad' value='Load'> </form>


Slightly off-topic, but: Note that client-side validation is no substitute for server-side validation. Client-side validation is purely to make it possible to provide a nicer user experience. For instance, if you don't allow uploading a file more than 5MB, you could use client-side validation to check that the file the user has chosen isn't more than 5MB in size and give them a nice friendly message if it is (so they don't spend all that time uploading only to get the result thrown away at the server), but you must also enforce that limit at the server, as all client-side limits (and other validations) can be circumvented.

JQuery在这个线程中提供的例子是非常过时的,谷歌没有任何帮助,所以这里是我的修订:

<script type="text/javascript">
  $('#image-file').on('change', function() {
    console.log($(this)[0].files[0].name+' file size is: ' + $(this)[0].files[0].size/1024/1024 + 'Mb');
  });
</script>