简体   繁体   English

JavaScript 文件上传大小验证

[英]JavaScript file upload size validation

有没有办法在使用 JavaScript 上传文件之前检查文件大小

Yes , you can use the File API for this.是的,您可以为此使用File API

Here's a complete example (see comments):这是一个完整的例子(见评论):

 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.例如,如果您不允许上传超过 5MB 的文件,您可以使用客户端验证来检查用户选择的文件大小是否不超过 5MB,如果是,则给他们一个友好的消息(因此他们不会花费所有时间上传只是为了在服务器上丢弃结果),但是您必须在服务器上强制执行该限制,因为可以规避所有客户端限制(和其他验证)。

Using jquery:使用jQuery:

<form action="upload" enctype="multipart/form-data" method="post">
                
    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />

    <script type="text/javascript">
        $('#image-file').bind('change', function() {
            alert('This file size is: ' + this.files[0].size/1024/1024 + "MiB");
        });
    </script>

</form>

Works for Dynamic and Static File Element适用于动态和静态文件元素

Javascript Only SolutionJavascript解决方案

 function validateSize(input) { const fileSize = input.files[0].size / 1024 / 1024; // in MiB if (fileSize > 2) { alert('File size exceeds 2 MiB'); // $(file).val(''); //for clearing with Jquery } else { // Proceed further } }
 <input onchange="validateSize(this)" type="file">

It's pretty simple.这很简单。

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;
}

No Yes, using the File API in newer browsers. 是,在较新的浏览器中使用 File API。 See TJ's answer for details.有关详细信息,请参阅 TJ 的回答。

If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.如果您还需要支持旧版浏览器,则必须使用基于 Flash 的上传器(如SWFUploadUploadify)来执行此操作。

The SWFUpload Features Demo shows how the file_size_limit setting works. SWFUpload 功能演示展示了file_size_limit设置的工作原理。

Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.请注意,这(显然)需要 Flash,而且它的工作方式与普通上传表单略有不同。

If you're using jQuery Validation, you could write something like this:如果您使用 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.'
);

I made something like that:我做了这样的事情:

 $('#image-file').on('change', function() { var numb = $(this)[0].files[0].size / 1024 / 1024; numb = numb.toFixed(2); if (numb > 2) { alert('to big, maximum is 2MiB. You file size is: ' + numb + ' MiB'); } else { alert('it okey, your file has ' + numb + 'MiB') } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input type="file" id="image-file">

Even though the question is answered, I wanted to post my answer.即使问题得到了回答,我还是想发布我的答案。 Might come handy to future viewers.You can use it like in the following code.可能对未来的观众有用。你可以像下面的代码一样使用它。

<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(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 + " bytesn"
              + "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");
    }
  }

I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications , along with another function with AJAX and changed according to my needs.我使用了在 Mozilla 开发者网络站点https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications 上找到的一个主要 Javascript 函数,以及带有 AJAX 的另一个函数,并根据我的需要进行了更改。 It receives a document element id regarding the place in my html code where I want to write the file size.它接收一个文档元素 ID,该 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>

Cheers干杯

JQuery example provided in this thread was extremely outdated, and google wasn't helpful at all so here is my revision:此线程中提供的 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>

You can try this fineuploader你可以试试这个fineuploader

It works fine under IE6(and above), Chrome or Firefox它在 IE6(及更高版本)、Chrome 或 Firefox 下运行良好

I ran across this question, and the one line of code I needed was hiding in big blocks of code.我遇到了这个问题,我需要的一行代码隐藏在大块代码中。

Short answer: this.files[0].size简短回答: this.files[0].size

By the way, no JQuery needed.顺便说一下,不需要 JQuery。

I use this script to validate file type and size我使用这个脚本来验证文件类型和大小

 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);" >

Simple way is简单的方法是

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

If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.如果您将 Ie 'Document Mode' 设置为 'Standards',您可以使用简单的 javascript 'size' 方法来获取上传文件的大小。

Set the Ie 'Document Mode' to 'Standards':将“文档模式”设置为“标准”:

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

Than, use the 'size' javascript method to get the uploaded file's size:然后,使用 'size' javascript 方法获取上传文件的大小:

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

It works for me.这个对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM