限制文件上传的大小(html 输入)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5697605/
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
Limit the size of an file upload (html input)
提问by delphi
I would like to simply limit the size of a file that a user can upload.
我想简单地限制用户可以上传的文件的大小。
I thought maxlength = 20000 = 20k but that doesn't seem to work at all.
我认为 maxlength = 20000 = 20k 但这似乎根本不起作用。
I am running on Rails, not PHP, but was thinking it'd be much simpler to do it client side in the HTML/CSS, or as a last resort using jQuery. This is so basic though that there must be some HTML tag I am missing or not aware of.
我在 Rails 上运行,而不是 PHP,但我认为在 HTML/CSS 中在客户端执行它会更简单,或者作为最后的手段使用 jQuery。这是非常基本的,尽管必须有一些我遗漏或不知道的 HTML 标签。
Looking to support IE7+, Chrome, FF3.6+. I suppose I could get away with just supporting IE8+ if necessary.
希望支持 IE7+、Chrome、FF3.6+。我想我可以在必要时只支持 IE8+。
Thanks.
谢谢。
回答by mark.inman
This is completely possible. Use Javascript.
这是完全可能的。使用 JavaScript。
I use jQuery to select the input element. I have it set up with an on change event.
我使用 jQuery 来选择输入元素。我已经设置了一个 on change 事件。
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
$("#approvedFiles").val(approvedHTML);
});
The code above saves all the file names that I deem worthy of persisting to the submission page, before the submit actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server side we do have to filter these out. I haven't written any code for that yet, but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and match them to the $_FILES(PHP Superglobal, sorry I dont know ruby file variable) variable.
上面的代码在提交实际发生之前保存了我认为值得保留到提交页面的所有文件名。我使用 jQuery 将“已批准”文件添加到输入元素的 val 中,以便表单提交将发送我想要保存的文件的名称。所有文件都将被提交,但是,现在在服务器端我们必须过滤掉这些文件。我还没有为此编写任何代码,但请发挥您的想象力。我假设可以通过 for 循环完成此操作并匹配从输入字段发送过来的名称,并将它们与 $_FILES(PHP Superglobal,抱歉我不知道 ruby 文件变量)变量匹配。
My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large wont be saved. This should work on all browsers because I'm not using FormData object.
我的观点是您可以在提交之前检查文件。我这样做,然后在他/她提交表单之前将其输出给用户,让他们知道他们正在上传到我的网站。任何不符合标准的东西都不会显示给用户,因此他们应该知道,不会保存太大的文件。这应该适用于所有浏览器,因为我没有使用 FormData 对象。
回答by Haseeb Rehman
var uploadField = document.getElementById("file");
uploadField.onchange = function() {
if(this.files[0].size > 2097152){
alert("File is too big!");
this.value = "";
};
};
This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.
这个例子应该可以正常工作。我将其设置为大约 2MB,以字节为单位的 1MB 为 1,048,576,因此您可以将其乘以所需的限制。
Here is the jsfiddle example for more clearence:
https://jsfiddle.net/7bjfr/808/
这是更清晰的 jsfiddle 示例:https://jsfiddle.net/7bjfr/808/
回答by Ortiga
You can't do it client-side. You'll have to do it on the server.
你不能在客户端做。您必须在服务器上执行此操作。
Edit: This answer is outdated!
编辑:这个答案已经过时了!
As the time of this edit, HTML file API is mostly supported on all major browsers.
截至本次编辑时,所有主流浏览器大多支持HTML 文件 API 。
I'd provide an update with solution, but @mark.inman.winning already did it.
我会提供解决方案的更新,但@mark.inman.spiring已经做到了。
Keep in mind that even if it's now possible to validate on the client, you should still validate it on the server, though. All client side validations can be bypassed.
请记住,即使现在可以在客户端进行验证,您仍然应该在服务器上进行验证。所有客户端验证都可以绕过。
回答by Yury Lavrukhin
const input = document.getElementById('input')
input.addEventListener('change', (event) => {
const target = event.target
if (target.files && target.files[0]) {
/*Maximum allowed size in bytes
5MB Example
Change first operand(multiplier) for your needs*/
const maxAllowedSize = 5 * 1024 * 1024;
if (target.files[0].size > maxAllowedSize) {
// Here you can ask your users to load correct file
target.value = ''
}
}
})
<input type="file" id="input" />
If you need to validate file type, write in comments below and I'll share my solution.
如果您需要验证文件类型,请写在下面的评论中,我将分享我的解决方案。
(Spoiler: accept
attribute is not bulletproof solution)
(剧透:accept
属性不是防弹解决方案)
回答by Fanda
Video file example (HTML + Javascript):
视频文件示例(HTML + Javascript):
<form action="some_script" method="post" enctype="multipart/form-data">
<input id="max_id" type="hidden" name="MAX_FILE_SIZE" value="250000000" />
<input onchange="upload_check()" id="file_id" type="file" name="file_name" accept="video/*" />
<input type="submit" value="Upload"/>
</form>
<script>
function upload_check()
{
var upl = document.getElementById("file_id");
var max = document.getElementById("max_id").value;
if(upl.files[0].size > max)
{
alert("File too big!");
upl.value = "";
}
};
</script>
回答by Ashadul Hoque Jahin
<script type="text/javascript">
$(document).ready(function () {
var uploadField = document.getElementById("file");
uploadField.onchange = function () {
if (this.files[0].size > 300000) {
this.value = "";
swal({
title: 'File is larger than 300 KB !!',
text: 'Please Select a file smaller than 300 KB',
type: 'error',
timer: 4000,
onOpen: () => {
swal.showLoading()
timerInterval = setInterval(() => {
swal.getContent().querySelector('strong')
.textContent = swal.getTimerLeft()
}, 100)
},
onClose: () => {
clearInterval(timerInterval)
}
}).then((result) => {
if (
// Read more about handling dismissals
result.dismiss === swal.DismissReason.timer
) {
console.log('I was closed by the timer')
}
});
};
};
});
</script>