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


当前回答

简单的方法是

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

其他回答

我使用了一个主要的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>

干杯

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

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

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

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

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

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

顺便说一下,不需要JQuery。

这很简单。

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

你可以试试这个fineuploader

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