[英]Checking file size limit
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.您需要从文件输入对象中获取文件,而您当前的代码正试图从
this
中获取它们,它指的是整个表单。
$("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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.