问题
I am uploading an image to the folder but before uploading, I am checking the image extension and size. I am using jQuery validation.
I checked on SO before uploading the question and I found the code. But the issue is when I am uploading an image which is less than 100kb(actual image size is 98kb) then I am getting the error "File size must be less than 5"
. I tried another image which is 3.8MB but still getting the same error.
Would you help me out what size of the image I have to use here? and what is the filesize: 5?
Can any one help me out in this issue?
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5,
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
回答1:
Your parameter is only set to 5
$('#form').validate({
rules: {
image: {
....
filesize: 5, ...
That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB. Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.
Try 5242880
if you want to allow files under 5 MB.
filesize: 5242880 // <- 5 MB
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5242880 // <- 5 MB
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
回答2:
Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly. For example if you want to check if the file size is less than 5MB, you should use
image: {
extension: "jpg,jpeg,png",
filesize: 5*1024*1024,
}
来源:https://stackoverflow.com/questions/54455000/checking-image-size-using-jquery-validation-not-working