我应该在循环中使用文件上传,例如
<form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1"onsubmit="return(validate());">
<?php for($i=0;$i<3;$i++)?>
<?php {?>
Select file:
<input name="ufile[]" type="file" id="file<?=$i;?>" size="50" />
<?php }?>
<input type="hidden" name="ivalue" value="3" id="someVar"/>
<input type="submit" name="Submit" value="Upload" />
</form>
我已经为文件上传提供了一些验证。像,
<script type="text/javascript">
function validate()
{
var x=document.getElementById("someVar").value;
for(i=0;i<x;i++)
{
var filename=document.getElementById('file'+i).value;
var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase();
if(filename)
{
if(extension=='png' || extension=='gif' || extension=='jpg' ||extension=='jpeg') {
return true;
} else {
alert('Allowed Extensions are "png","gif" and "jpg" !');
return false;
}
return true;
}
else
{
alert('Select upload files!');
return false;
}
}
}
</script>
但我的脚本只验证第一个文件。(我知道这是由于id命名约定)。但是我需要验证,如果用户没有选择任何文件。我怎么能这样做?我的意思是,我怎样才能对for循环中的所有文件进行验证?
谢谢!
答案 0 :(得分:2)
<script type="text/javascript">
function validate()
{
var x=document.getElementById("someVar").value;
for(i=0;i<x;i++) {
var filename=document.getElementById('file'+i).value;
var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase();
if (filename) {
if (extension=='png' || extension=='gif' || extension=='jpg' ||extension=='jpeg') {
} else {
alert('Allowed Extensions are "png","gif" and "jpg" !');
return false;
}
} else {
alert('Select upload files!');
return false;
}
}
return true;
}
</script>
答案 1 :(得分:1)
$(document)
.click(
function() {
$("#uploadId")
.change(
function() {
var f = this.files[0];
var p = f.size;
var fup = document
.getElementById('uploadId');
var fileName = fup.value;
var ext = fileName
.substring(fileName
.lastIndexOf('.') + 1);
if (ext == "GIF" || ext == "gif"
|| ext == "jpg"
|| ext == "JPG"
|| ext == "jpeg"
|| ext == "JPEG"
|| ext == "bmp"
|| ext == "BMP"
|| ext == "png"
|| ext == "PNG") {
if ((p <= 2097152)) {
return true;
}
else {
alert("Please upload the image max.size of 2 MB");
$("#uploadId").val('');
$("#uploadId").attr(
'enabled',
'enabled');
}
} else {
alert("Please upload the images only");
$("#uploadId").val('');
$("#uploadId").attr('enabled',
'enabled');
}
});
});