日期:2014-05-17 浏览次数:20476 次
<form name="myform" action="upload.php" method="post" enctype="multipart/form-data"> 产品名称: <input type="text" name="pname" /> <br /> 产品图片1:<input type="file" name="pic1"> <br /> 产品图片2:<input type="file" name="pic2"> <br /> 产品图片3:<input type="file" name="pic3"> <br /> 产品图片4:<input type="file" name="pic4"> <p /> <input type="hidden" name="MAX_FILE_SIZE" value="2000000" /> <input type="submit" name="submit" value="提交"> </form>
<?php $uploaddir = "../images/upfiles/";//图片存放文件夹,如果不存在,就创建(得有权限) if(!file_exists($uploaddir)) { mkdir($uploaddir); } $type=array("jpg","gif","bmp","jpeg","png");//限定上传文件的格式 $patch="testupload/";//上传类所在的路径---这个可选填 function fileext($filename)//取得上传文件的扩展名(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法) { return substr(strrchr($filename, '.'), 1); } function random($length)//取得随机数,好像是用哈希算法得到的(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法) { $hash = 'CR-'; $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; $max = strlen($chars) - 1; mt_srand((double)microtime() * 1000000); for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; } $a=strtolower(fileext($_FILES['pic']['name']));//这里的pic就是你HTML表单里的图片域的name="pic"(上传多个图片时,需要分别对其重命名,否则会报错说函数多次声明违法) if(!in_array(strtolower(fileext($_FILES['pic']['name'])),$type))//这里记得对应改函数名和pic的名字 { $text=implode(",",$type); echo "You can only upload the following types of files:",$text,"<br /> <a href='upload_pro.php'>return and try again?click me</a>"; exit; } else{ $filename=explode(".",$_FILES['pic']['name']);//同上,pic需要对应改名 do { $filename[0]=random(10); //用到函数random时,一样要对应改名 $name=implode(".",$filename); //$name1=$name.".Mcncc"; $uploadfile=$uploaddir.$name;//这个$uploadfile就是你要插入数据库相应字段的图片路径,需要相应做变化 } while(file_exists($uploadfile));//函数名需要对应最变更 if (move_uploaded_file($_FILES['pic']['tmp_name'],$uploadfile))//PIC需要对应最变更 { if(is_uploaded_file($_FILES['pic']['tmp_name']))//pic需要对应做变更 { echo "the Images Upload failed!"; } else { echo "<center>Your file has been uploaded: </center><br><center><img src='$uploadfile' /></center>";//src=后面也要对应最变更 echo "<br><center><a href='upload_pro.php'>Continue to upload</a></center>"; } } } ?>
------解决方案--------------------
一个测试例
<form name="myform" method="post" enctype="multipart/form-data"