JavaScript 文件上传大小验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3717793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript file upload size validation
提问by ArK
Is there any way to check file sizebefore uploading it using JavaScript?
有没有办法在使用 JavaScript 上传文件之前检查文件大小?
回答by T.J. Crowder
Yes, there's a new feature from the W3C that's supported by some modern browsers, the File API. It can be used for this purpose, and it's easy to test whether it's supported and fall back (if necessary) to another mechanism if it isn't.
是的,有些现代浏览器支持 W3C 的一项新功能,即File API。它可以用于此目的,并且很容易测试它是否受支持,如果不支持,则退回(如有必要)到另一种机制。
Here's a complete example:
这是一个完整的例子:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileSize() {
var input, file;
// (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) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
}
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
</form>
</body>
</html>
And hereit is in action. Try that with a recent version of Chrome or Firefox.
而这里是它的行为。尝试使用最新版本的 Chrome 或 Firefox。
Slightly off-topic, but: Note that client-side validation is no substitutefor 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 alsoenforce that limit at the server, as all client-side limits (and other validations) can be circumvented.
稍微偏离主题,但是:请注意,客户端验证不能替代服务器端验证。客户端验证纯粹是为了提供更好的用户体验。例如,如果您不允许上传超过 5MB 的文件,您可以使用客户端验证来检查用户选择的文件大小是否不超过 5MB,如果是,则给他们一个友好的消息(因此他们不会花费所有时间上传只是为了在服务器上丢弃结果),但是您还必须在服务器上强制执行该限制,因为可以规避所有客户端限制(和其他验证)。
回答by Ben
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 + "MB");
});
</script>
</form>
回答by Arun Prasad E S
Works for Dynamic and Static File Element
适用于动态和静态文件元素
JavascriptOnly Solution
仅Javascript解决方案
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
if (FileSize > 2) {
alert('File size exceeds 2 MB');
// $(file).val(''); //for clearing with Jquery
} else {
}
}
<input onchange="ValidateSize(this)" type="file">
回答by Hasan Tuna Oru?
It's pretty simple.
这很简单。
var oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 mb for bytes.
{
alert("File size must under 2mb!");
return;
}
回答by Pekka
NoYes, using the File API in newer browsers. See TJ's answer for details.
否是,在较新的浏览器中使用 File API。有关详细信息,请参阅 TJ 的回答。
If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUploador Uploadifyto do this.
如果您还需要支持旧版浏览器,则必须使用基于 Flash 的上传器(如SWFUpload或Uploadify)来执行此操作。
The SWFUpload Features Demoshows 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,而且它的工作方式与普通上传表单略有不同。
回答by Nikolaos Georgiou
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 2MB.'
);
回答by Jose Gaspar
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. It receives a document element id regarding the place in my html code where I want to write the file size.
我使用了在 Mozilla 开发者网络站点https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications 上找到的一个主要 Javascript 函数,以及另一个带有 AJAX 的函数,并根据我的需要进行了更改。它接收一个文档元素 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
干杯
回答by Lemon Kazi
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 5MB!');
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
回答by nodws
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>
回答by kibus90
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 2MB. You file size is: ' + numb +' MB');
} else {
alert('it okey, your file has ' + numb + 'MB')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">