[英]javascript accept only image not working
In my code I want to accept only image file
.otherwise it will not accept and will give alert that its not image file
. 在我的代码中,我只想接受
image file
否则它将不接受并且会发出警告,提示它不是image file
。
I have done below code in jsfiddle:-- 我在jsfiddle中完成了以下代码:-
but the problem is it..It is not giving any message.what am I doing wrong? 但是问题就在这里。它没有发出任何消息。我在做什么错?
https://jsfiddle.net/weufx7dy/2/ https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element 您忘记在文件元素上添加ID
<input type="file" id="file" name="fileUpload" size="50" />
You had used 你曾经用过
var image =document.getElementById("file").value;
but forgot to give id to file control so give that 但忘了给文件控制赋予ID,所以给
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit 并尝试在w3schools tryit浏览器中遵循以下代码,并在“提交”按钮而不是onSubmit上使用onClick事件
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this : 用这个 :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.