我正在使用 uploadify 来上传 Codeigniter 中的文件。在上传文件之前,我需要检查文件扩展名是否正确。我已经尝试了 http://jquery.bassistance.de/ 和 http://forum.jquery.com/,但并未得到期望的结果。请问有人可以告诉我如何实现吗?
<input type="file" id="FilUploader" />
JQuery
的翻译是JQuery
。 $("#FilUploader").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only formats are allowed : "+fileExtension.join(', '));
}
});
了解更多信息请点击此处
lastIndexOf('.')
代替split()
会更好,这样可以确保使用的是最后一个点,它表示文件扩展名。 - Felipe Leãopop()
的意思是从数组中取出最后一个元素。 - Eli$(document).ready( function (){
$("#your_form").submit( function(submitEvent) {
// get the file name, possibly with path (depends on browser)
var filename = $("#file_input").val();
// Use a regular expression to trim everything before final dot
var extension = filename.replace(/^.*\./, '');
// Iff there is no dot anywhere in filename, we would have extension == filename,
// so we account for this possibility now
if (extension == filename) {
extension = '';
} else {
// if there is an extension, we convert to lower case
// (N.B. this conversion will not effect the value of the extension
// on the file upload.)
extension = extension.toLowerCase();
}
switch (extension) {
case 'jpg':
case 'jpeg':
case 'png':
alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)");
// uncomment the next line to allow the form to submitted in this case:
// break;
default:
// Cancel the form submission
submitEvent.preventDefault();
}
});
});
HTML:
<form id="your_form" method="post" enctype="multipart/form-data">
<input id="file_input" type="file" />
<input type="submit">
</form>
我想感谢那个发布了答案的人,但他已经删除了帖子。我们可以这样做。
$("#yourElem").uploadify({
'uploader': ...,
'script': ...
'fileExt' : '*.jpg;*.gif;', //add allowed extensions
.....,
'onSelect': function(e, q, f) {
var validExtensions = ['jpg','gif']; //array of valid extensions
var fileName = f.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1){
alert("Invalid file type");
$("#yourElem").uploadifyCancel(q);
return false;
}
}
});
谢谢您的回答,它真的很有效...
这是一段简单的javascript校验代码,当校验通过后,它将清理输入文件。
<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>
function validate(file) {
var ext = file.split(".");
ext = ext[ext.length-1].toLowerCase();
var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];
if (arrayExtensions.lastIndexOf(ext) == -1) {
alert("Wrong extension type.");
$("#image").val("");
}
}
$("#file-upload").change(function () {
var validExtensions = ["jpg","pdf","jpeg","gif","png"]
var file = $(this).val().split('.').pop();
if (validExtensions.indexOf(file) == -1) {
alert("Only formats are allowed : "+validExtensions.join(', '));
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('.form-file input').each(function () {
$this = jQuery(this);
$this.on('change', function() {
var fsize = $this[0].files[0].size,
ftype = $this[0].files[0].type,
fname = $this[0].files[0].name,
fextension = fname.substring(fname.lastIndexOf('.')+1);
validExtensions = ["jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","pptx","txt","zip","rar","gzip"];
if ($.inArray(fextension, validExtensions) == -1){
alert("This type of files are not allowed!");
this.value = "";
return false;
}else{
if(fsize > 3145728){/*1048576-1MB(You can change the size as you want)*/
alert("File size too large! Please upload less than 3MB");
this.value = "";
return false;
}
return true;
}
});
});
});
</script>
</head>
<body>
<form>
<div class="form-file">
<label for="file-upload" class="from-label">File Upload</label>
<input class="form-control" name="file-upload" id="file-upload" type="file">
</div>
</form>
</body>
</html>
以下是检查文件大小和文件扩展名的完整代码。它使用默认文件输入字段和 jQuery 库。
var extension = $('#your_file_id').val().split('.').pop().toLowerCase();
if($.inArray(extension, ['gif','png','jpg','jpeg','bmp']) == -1) {
alert('Sorry, invalid extension.');
return false;
}
$(this).val()
,可以尝试:var file_onchange = function () {
var input = this; // avoid using 'this' directly
if (input.files && input.files[0]) {
var type = input.files[0].type; // image/jpg, image/png, image/jpeg...
// allow jpg, png, jpeg, bmp, gif, ico
var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;
if (type_reg.test(type)) {
// file is ready to upload
} else {
alert('This file type is unsupported.');
}
}
};
$('#file').on('change', file_onchange);
function yourfunctionName() {
var yourFileName = $("#yourinputfieldis").val();
var yourFileExtension = yourFileName .replace(/^.*\./, '');
switch (yourFileExtension ) {
case 'pdf':
case 'jpg':
case 'doc':
$("#formId").submit();// your condition what you want to do
break;
default:
alert('your File extension is wrong.');
this.value = '';
}
}