Limit the size of a file upload (html input element)
HtmlHtml Problem Overview
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.
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.
Looking to support IE7+, Chrome, FF3.6+. I suppose I could get away with just supporting IE8+ if necessary.
Thanks.
Html Solutions
Solution 1 - Html
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.
Here is the jsfiddle example for more clearence:
https://jsfiddle.net/7bjfr/808/
Solution 2 - Html
This is completely possible. Use Javascript.
I use jQuery to select the input element. I have it set up with an on change event.
$("#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.
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.
Solution 3 - Html
You can't do it client-side. You'll have to do it on the server.
Edit: This answer is outdated!
When I originally answered this question in 2011, HTML File API was nothing but a draft. It is now supported on all major browsers.
I'd provide an update with solution, but @mark.inman.winning has already answered better than I could.
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.
Solution 4 - Html
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)
Solution 5 - Html
Video file example (HTML + Javascript):
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 = "";
}
};
<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>
Solution 6 - Html
This question was from a long time ago, but maybe this could help someone struggling. If you are working with forms, the easiest way to do this is by creating a new FormData with your form. For example:
form.addEventListener("submit", function(e){
e.preventDefault()
const fd = new FormData(this)
for(let key of fd.keys()){
if(fd.get(key).size >= 2000000){
return console.log(`This archive ${fd.get(key).name} is bigger than 2MB.`)
}
else if(fd.get(key).size < 2000000){
console.log(`This archive ${fd.get(key).name} is less than 2MB.`)
}
else{
console.log(key, fd.get(key))
}
}
this.reset()
})
As you can see, you can get the size from an archive submited with a form by typing this:
fd.get(key).size
And the file name is also reachable:
fd.get(key).name
Hope this was helpful!
Solution 7 - Html
I made a solution using just JavaScript, and it supports multiple files:
const input = document.querySelector("input")
const result = document.querySelector("p")
const maximumSize = 10 * 1024 * 1024 // In MegaBytes
input.addEventListener("change", function(e){
const files = Array.from(this.files)
const approvedFiles = new Array
if(!files.length) return result.innerText = "No selected files"
for(const file of files) if(file.size <= maximumSize) approvedFiles.push(file)
if(approvedFiles.length) result.innerText = `Approved files: ${approvedFiles.map(file => file.name).join(", ")}`
else result.innerText = "No approved files"
})
<input type="file" multiple>
<p>Result</p>
Solution 8 - Html
<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>
Solution 9 - Html
PHP solution to verify the size in the hosting.
<?php
if ($_FILES['name']['size'] > 16777216) {
?>
<script type="text/javascript">
alert("The file is too big!");
location.href = history.back();
</script>
<?php
die();
}
?>
16777216 Bytes = 16 Megabytes
Convert units: https://convertlive.com/u/convert/megabytes/to/bytes#16
Adapted from https://www.php.net/manual/en/features.file-upload.php