i need help in checking file size before uploading file,
i want to check the size of file and then continue to upload
$("form#data").submit(function(e) {
e.preventDefault();
if(this.files[0].size > 2097152){
alert("File is too big!");
this.value = "";
return false;
};
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
<form id="data" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form>
You need to get the files from the file input object whereas your current code is trying to get them from this
which refers to the entire form.
$("form#data").submit(function(e) { e.preventDefault(); const file_input = $(this).find('input[name="image"]')[0]; console.log(file_input.files[0].size); if (file_input.files[0].size > 2097152) { alert("File is too big!"); this.value = ""; return false; }; console.log("safe to upload..."); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="data" method="post" enctype="multipart/form-data"> <input name="image" type="file" /> <button>Submit</button> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.