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


否是,在较新的浏览器中使用File API。详见TJ的回答。

如果你也需要支持旧的浏览器,你将不得不使用基于flash的上传器,如SWFUpload或Uploadify来做到这一点。

SWFUpload Features Demo展示了file_size_limit设置是如何工作的。

注意,这(显然)需要Flash,加上它的工作方式与正常的上传表单有点不同。

是的,您可以为此使用文件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.

你可以试试这个fineuploader

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

使用jquery:

$(" #图像文件”)。On ('change', function() { console.log('This file size is: ' + This .files[0]. log)size / 1024 / 1024 + "MiB"); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js " > < /脚本> <form action="upload" enctype="multipart/form-data" method="post"> 上传图片: <input id="image-file" type="file" name="file" /> <input type="submit" value="Upload" /> > < /形式

如果你正在使用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.'
);

我使用了一个主要的Javascript函数,这个函数是我在Mozilla开发者网络站点https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications上找到的,还有一个使用AJAX的函数,并根据我的需要进行了修改。它接收到一个文档元素id,关于在我的html代码中我想写文件大小的地方。

<Javascript>

function updateSize(elementId) {
    var nBytes = 0,
    oFiles = document.getElementById(elementId).files,
    nFiles = oFiles.length;

    for (var nFileId = 0; nFileId < nFiles; nFileId++) {
        nBytes += oFiles[nFileId].size;
    }
    var sOutput = nBytes + " bytes";
    // optional code for multiples approximation
    for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
    }

    return sOutput;
}
</Javascript>

<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>

<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>

干杯

如果你将Ie的“文档模式”设置为“标准”,你可以使用简单的javascript“大小”方法来获取上传文件的大小。

将Ie的文档模式设置为标准模式:

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

然后,使用'size' javascript方法获取上传文件的大小:

<script type="text/javascript">
    var uploadedFile = document.getElementById('imageUpload');
    var fileSize = uploadedFile.files[0].size;
    alert(fileSize); 
</script>

这对我很管用。

这很简单。

const oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>

if (oFile.size > 2097152) // 2 MiB for bytes.
{
  alert("File size must under 2MiB!");
  return;
}

尽管问题已经有了答案,我还是想把我的答案贴出来。可能对以后的观众有用。您可以像下面的代码中那样使用它。

document.getElementById("fileinput").addEventListener("change",function(evt) { //Retrieve the first (and only!) File from the FileList object var f = evt.target.files[0]; if (f) { var r = new FileReader(); r.onload = function(e) { var contents = e.target.result; alert("Got the file\n" + "name: " + f.name + "\n" + "type: " + f.type + "\n" + "size: " + f.size + " bytes\n" + "starts with: " + contents.substr(1, contents.indexOf("\n")) ); if (f.size > 5242880) { alert('File size Greater then 5MiB!'); } } r.readAsText(f); } else { alert("Failed to load file"); } }) <input type="file" id="fileinput" />

适用于动态和静态文件元素

仅Javascript解决方案

函数validateSize(input) { const fileSize = input.files[0]。Size / 1024 / 1024;// in MiB if (fileSize > 2) { alert('文件大小超过2个MiB'); / / $(文件).val (");//使用Jquery清除 }其他{ //继续 } } <input onchange="validateSize(this)" type="file">

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>

我做了这样的东西:

$(" #图像文件”)。On ('change', function() { Var numb = $(this)[0].files[0]。Size / 1024 / 1024; numb = number . tofixed (2); If (numb > 2) { alert('to big,最大值为2MiB。你的文件大小是:' + numb + ' MiB'); }其他{ alert('it okey,你的文件有' + numb + 'MiB') } }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js " > < /脚本> <input type="file" id="image-file">

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

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

顺便说一下,不需要JQuery。

简单的方法是

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

我使用这个脚本来验证文件类型和大小

var _validFilejpeg = [".jpeg", ".jpg", ".bmp", ".pdf"]; function validateForSize(oInput, minSize, maxSizejpeg) { //if there is a need of specifying any other type, just add that particular type in var _validFilejpeg if (oInput.type == "file") { var sFileName = oInput.value; if (sFileName.length > 0) { var blnValid = false; for (var j = 0; j < _validFilejpeg.length; j++) { var sCurExtension = _validFilejpeg[j]; if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length) .toLowerCase() == sCurExtension.toLowerCase()) { blnValid = true; break; } } if (!blnValid) { alert("Sorry, this file is invalid, allowed extension is: " + _validFilejpeg.join(", ")); oInput.value = ""; return false; } } } fileSizeValidatejpeg(oInput, minSize, maxSizejpeg); } function fileSizeValidatejpeg(fdata, minSize, maxSizejpeg) { if (fdata.files && fdata.files[0]) { var fsize = fdata.files[0].size /1024; //The files property of an input element returns a FileList. fdata is an input element,fdata.files[0] returns a File object at the index 0. //alert(fsize) if (fsize > maxSizejpeg || fsize < minSize) { alert('This file size is: ' + fsize.toFixed(2) + "KB. Files should be in " + (minSize) + " to " + (maxSizejpeg) + " KB "); fdata.value = ""; //so that the file name is not displayed on the side of the choose file button return false; } else { console.log(""); } } } <input type="file" onchange="validateForSize(this,10,5000);" >