在使用JavaScript上传文件之前,有什么方法可以检查文件大小?
当前回答
我使用了一个主要的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>
干杯
其他回答
你可以试试这个fineuploader
它在IE6(及以上版本)、Chrome或Firefox下运行良好
我做了这样的东西:
$(" #图像文件”)。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">
适用于动态和静态文件元素
仅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">
简单的方法是
const myFile = document.getElementById("fileUpload").files[0];
if (myFIle.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}
是的,您可以为此使用文件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.
推荐文章
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- jQuery日期/时间选择器