如何将输入文件设置回"没有选择文件"如果文件格式不是图像格式?
<input type="file" name="image" id="image" value="" class="form-control" />
<script>
$("#image").change(function()
{
var Data = document.getElementById('image');
var FileUploadPath = Data.value;
if (FileUploadPath != '') {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg"){
return true;
}else if (Extension != 'gif' || Extension != 'png' || Extension != 'bmp' || Extension != 'jpeg' || Extension != 'jpg') {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
return false;
}
}
});
</script>
答案 0 :(得分:1)
$("#image").change(function()
{
var Data = document.getElementById('image');
var FileUploadPath = Data.value;
if (FileUploadPath != '') {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg"){
return true;
}else if (Extension != 'gif' || Extension != 'png' || Extension != 'bmp' || Extension != 'jpeg' || Extension != 'jpg') {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
Data.type = '';
Data.type = 'file';
return false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="image" id="image" value="" class="form-control" />
答案 1 :(得分:0)
您可以将值设置为空字符串
$("#image").change(function()
{
var Data = document.getElementById('image');
var FileUploadPath = Data.value;
if (FileUploadPath !== '') {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg" || Extension == "jpg"){
return true;
}else if (Extension != 'gif' || Extension != 'png' || Extension != 'bmp' || Extension != 'jpeg' || Extension != 'jpg') {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
Data.value = "";
return false;
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>File Upload</title>
</head>
<body>
<input type="file" name="image" id="image" value="" class="form-control" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>