PHP 批量上传文件 大全

案例一:

<?php
$file_path="uploads/";
for($i=0;$i<count($_FILES[ufile][name]);$i++){
 

  $_FILES[ufile][name][$i]=time().$_FILES[ufile][name][$i]; //加个时间戳防止重复文件上传后被覆盖
   
}
print_r($_FILES[ufile][name]);
$filename=$_FILES[ufile][name];
$filet=$_FILES[ufile][tmp_name];
if($filet[size]>"500000"){   //这个可以自己随便改
   echo "您上传的文件大小为".$_FILES['ufile'][size]."大于500kb,请重新上传";
}else if($filet){
   for($i=0;$i<count($filename);$i++){     //循环上传文件的数组
     move_uploaded_file($filet[$i],$file_path.$filename[$i]);
   }
}
else{
    echo "文件上传失败";
   }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>无标题文档</title>
</head>
<body>
<p>请上传问件不大于500K</p>
<form method="post" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="ufile[]" />
    <input type="file" name="ufile[]" />
    <input type="file" name="ufile[]" />
    <input type="submit" value="提交" />
   
</form>
</body>
</html>

案例二:
php动态批量上传文件

<?php
function upload_multi($path,$photo,$i){
$uploaddir = './'.$path;//文件存放目录
if(!file_exists($uploaddir))//如果目录不存在就新建
$uploaddir=mkdir($uploaddir);

$piece = explode('.',$photo['name'][$i]);
$uploadfile = $uploaddir . '/'.md5($piece[0]).'.'.$piece[1];
$result = move_uploaded_file($photo['tmp_name'][$i], $uploadfile);
if(!$result){
exit('上传失败');
}
return basename($uploadfile);
}

if($_POST['tijiao']){
extract($_POST);
$i=0;
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
upload_multi($email,$_FILES["pictures"],$i);
}
$i++;
}
}
?>
<script language="javascript">
function go_up(){
document.getElementByIdx_x_x_x_x_x('new_up').innerHTML+='<input type="file" name="pictures[]" /><br>';
}
</script>
<form action="file.php" method="post" enctype="multipart/form-data">
<p>多图片上传<br>
<input type="text" name="username" /><br>
<input type="text" name="email" /><br>
<input type="file" name="pictures[]" /><br>
<div id="new_up"></div>
<input type="button" " name="add_img" value="新增上传" οnclick="go_up()" /><br>
<input type="submit" value="Send" name="tijiao" /><br>
</p>
</form>

案例三:
php文件上传代码(支持文件批量上传)

本款文件上传类,默认是上传单文件的,我们只要修改$inputname ='files’为你的表单名就可以方便的实现批量文件上传了。 $savename = ''保存文件名, a l o w e x t s = a r r a y ( ) 设置允许上传的类型, alowexts = array()设置允许上传的类型, alowexts=array()设置允许上传的类型,savepath = ''保存路径。

*/  
 
class upload  
{  
public $savepath;  
public $files;  
private $error;  
 
function __construct($inputname ='files', $savepath = '', $savename = '', $alowexts = array(),$maxsize = 1024000)  
{  
if(!$alowexts)$alowexts=explode('|',upload_ftype);  
$file_array=array();  
$savepath=str_replace('','/',$savepath);  
$savename=preg_replace('/[^a-z0-9_]+/i','',$savename);  
$this->savepath=substr($savepath,-1)=='/'?$savepath:$savepath.'/'; //路径名以/结尾  
 
if(!make_dir($this->savepath))  
{  
$this->error=8;  
$this->error();  
}  
//exit($this->savepath);  
if(!is_writeable($this->savepath))  
{  
$this->error=9;  
$this->error();  
}  
if(sizeof($_files[$inputname]['error'])>10)  
{  
$this->error=13;  
$this->error();  
}  
$max=sizeof($_files[$inputname]['error'])-1;  
//exit($this->savepath.$savename);  
foreach($_files[$inputname]['error'] as $key => $error)  
{  
if($error==upload_err_ok) //批量上传  
{  
$savename=$savename?$savename:date('ymdims').mt_rand(10000,99999);   
$fileext=strtolower(get_fileext($_files[$inputname]['name'][$key]));  
$savename=$savename.'.'.$fileext;  
$tmp_name=$_files[$inputname]['tmp_name'][$key];  
$filesize=$_files[$inputname]['size'][$key];  
if(!in_array($fileext,$alowexts))  
{  
$this->error=10;  
$this->error();  
}  
if($filesize>$maxsize)  
{  
$this->error=11;  
$this->error();  
}  
if(!$this->isuploadedfile($tmp_name))  
{  
$this->error=12;  
$this->error();  
}  
 
if(move_uploaded_file($tmp_name,$this->savepath.$savename) || @copy($tmp_name,$this->savepath.$savename))  
{  
//exit($this->savepath.$savename);  
@chmod($savename, 0644);  
@unlink($tmp_name);  
$file_array[]=$this->savepath.$savename;   
}  
}  
else 
{  
$this->error=$error;  
$this->error();  
}  
unset($savename);  
}  
$this->files=$file_array;  
return true;  
}  
 
function isuploadedfile($file) //去掉系统自带的反斜线  
{  
return (is_uploaded_file($file) || is_uploaded_file(str_replace('\','',$file)));   
}  
 
function error()  
{  
$upload_error=array(0 => '文件上传成功 !',  
1 => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值 !',  
2 => '上传文件的大小超过了 html 表单中 max_file_size 选项指定的值 !',  
3 => '文件只有部分被上传 !',  
4 => '没有文件被上传 !',  
5 => '未知错误!',  
6 => '找不到临时文件夹。 !',  
7 => '文件写入临时文件夹失败 !',  
8 => '附件目录创建失败 !',  
9 => '附件目录没有写入权限 !',  
10 => '不允许上传该类型文件 !',  
11 => '文件超过了管理员限定的大小 !',  
12 => '非法上传文件 !',  
13 => '最多可同时上传10个文件 !' 
);  
showmsg($upload_error[$this->error]);  
}  
 
}  
//使用方法  
 
new upload();

案例四:PHP文件批量上传类

<?php

class upFiles

{

    

    public $uploadFiles = array();

    

    public $saveFilePath;

    

    public $maxFileSize;

    

    public $lastError;

    

    public $allowType = array('gif','jpg','png','bmp');

    

    public $finalFilePath;

    

    public $saveFileInfo = array();

    

    public function __construct($file,$path,$size= 2097152,$type = '')

    {

        $this->uploadFiles     = $file;

        $this->saveFilePath = $path;

        $this->maxFileSize     = $size;

        if($type != '') $this->allowType = $type;

    }

    public function upload()

    {

        for($i=0;$i<count($this->uploadFiles['name']);$i++)

        {

            //如果文件上传没有出现错误

            if($this->uploadFiles['error'][$i] == 0)

            {

                //获取当前文件名,临时文件名,文件大小,扩展名

                $name             = $this->uploadFiles['name'][$i];

                $tmpname     = $this->uploadFiles['tmp_name'][$i];

                $size             = $this->uploadFiles['size'][$i];

                $minetype     = $this->uploadFiles['type'][$i];

                $type             = $this->getFileExt($this->uploadFiles['name'][$i]);

                //检查文件大小是否合法

                if(!$this->checkSize($size))

                {

                    $this->lastError = "文件大小超出限制.文件名称:".$name;

                    $this->printMsg($this->lastError);

                    continue;

                }

                //检查文件扩展名是否合法

                if(!$this->checkType($type))

                {

                    $this->lastError = "非法的文件类型.文件名称:".$name;

                    $this->printMsg($this->lastError);

                    continue;

                }

                //检测当前文件是否非法提交

                if(!is_uploaded_file($tmpname))

                {

                    $this->lastError = "上传文件无效.文件名称:".$name;

                    $this->printMsg($this->lastError);

                    continue;

                }

                //移动后的文件名称

                $basename = $this->getBaseName($name,'.'.$type);

                //上传文件重新命名,格式为 UNIX时间戳+4位随机数,生成一个14位文件名

                $savename = time().mt_rand(1000,9999).'.'.$type;

                //创建上传文件的文件夹

                @mkdir($this->saveFilePath);

                $file_name1 = $this->saveFilePath.'/'.date('Y');

                @mkdir($file_name1);

                $file_name2 = $this->saveFilePath.'/'.date('Y').'/'.date('m');

                @mkdir($file_name2);

                //最终组合的文件路径

                $this->finalFilePath = $file_name2.'/'.$savename;

                //把上传的文件从临时目录移到目标目录

                if(!move_uploaded_file($tmpname,$this->finalFilePath))

                {

                    $this->$this->uploadFiles['error'][$i];

                    $this->printMsg($this->lastError);

                    continue;

                }

                //存储已经上传的文件信息

                $this->saveFileInfo = array(

                    'name'            => $name,

                    'type'            => $type,

                    'minetype'        => $minetype,

                    'size'                => $size,

                    'savename'    => $savename,

                    'path'            => $this->finalFilePath,

                );

            }

        }

        //返回上传的文件数量

        return count($this->saveFileInfo);

    }

    

    public function getSaveFileInfo()

    {

        return $this->saveFileInfo;

    }

    

    private function checkSize($size)

    {

        return $size > $this->maxFileSize) ? false : true;;

    }

    

    private function checkType($etype)

    {

        foreach($this->allowType as $type)

        {

            if(strcasecmp($etype,$type) == 0) return true;

        }

        return false;

    }

    

    private function printMsg($msg)

    {

        return $msg;

    }

    

    private function getFileExt($filename)

    {

        $ext = pathinfo($filename);

        return $ext['extension'];

    }

    

    private function getBaseName($filename,$type)

    {

        $basename = basename($filename,$type);

        return $basename;

    }

}

?>

案例五:php批量上传,里面没写上php的文件名们应该是:up.php

PHP批量上传文件

以下是本人做的一个批量上传的php程序,请参考!

首先,创建一个upload.html;内容如下:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; cha$resultet=utf-8" />

<title>

</title>

<script language="javascript">

function upload(id){

div = document.getElementByIdx_x_x('light');

div.style.display='block';

document.getElementByIdx_x_x('fade').style.display='block';

childs = div.childNodes;

for(i=0;i<childs.length;i++){

if(childs[i].nodeName.toUpperCase() == "IFRAME"){

childs[i].src="funs/up.php?label="+id;

}

}

}

 

//删除元素

function delpic(id){

a = document.getElementByIdx_x_x("pics");

child = document.getElementByIdx_x_x("span"+id);

a.removeChild(child);

}

 

//添加元素

function create(id){

span = document_createElement_x_x("span");

span.id               = "span"+id;

span.style.display    = "block";

span.style.height     = "22px";

span.style.lineHeight = "22px";

span.innerHTML = "名称: <input type='text' name='pic_name[]' id='pic_name"+id +"' size='20'>  地址: <input type='text' name='pic_url[]' id='pic_url"+id +"' size='30'> [<a href='javascript:' onClick='upload("+id+")'><font color='#FF0000'>上传更换图片</font></a>] [<a href='javascript:delpic("+id+")'>移除</a>]";

return span;

}

function add_upload(){

div = document.getElementByIdx_x_x("pics");

mynum = parseInt(document.getElementByIdx_x_x("num").value,10);

//mynum = document.getElementByIdx_x_x("num").value;

document.getElementByIdx_x_x("num").value = mynum+1;

obj = create(mynum);

div.a(obj);

}

</script>

<style type="text/css">

.white_content {

display:none;

position:absolute;

width:40%;

top:25%;

left:30%;

z-index:9999;

background-color:#fff;

}

.black_overlay{

display:none;

width:100%;

height:100%;

background-color:#ccc;

position:absolute;

top:0;

left:0;

z-index:1;

filter: Alpha(opacity=50);    

-moz-opacity:.5;    

opacity:0.5;    

   }

</style>

</head>

<body>

<div id="light" class="white_content">

  <div class="white_top"><a href="javascript:void(0)" onclick="document.getElementByIdx_x_x('light').style.display='none';document.getElementByIdx_x_x('fade').style.display='none'"> 关闭</a></div>

  <iframe src="funs/up.php" width="100%" height="auto" scrolling="auto" frameborder="0" style="clear:both; padding-top:5px;"></iframe>

</div>

<div id="fade" class="black_overlay"></div>

  <div class="right">

    <div class="right_body">

<table class="tab">

             <tr>

          <td align="center">人物照片:

            </td>

          <td><div id="pics"> <span id="span0">名称:

              <input type="text" size="20" id="pic_name0" name="pic_name[]">

               地址:

              <input type="text" size="30" id="pic_url0" name="pic_url[]">

              [<a href="javascript:" onclick="upload(0)"><font color="#ff0000">上传更换图片</font></a>]</span> 

              <input type="button" value="添加上传文件" onclick="add_upload()" >

              </div>

<input type="hidden" id="num" name="num" value="1"  >    

             </td>

        </tr>

          </table>

    </div>

</div>

</body>

</html>

然后在本目录创建一个funs的文件夹,人后在里面创建一个php文件,放在,内容如下:

//上传文件类型列表

$uptypes=array(

    'image/jpg',

    'image/jpeg',

    'image/png',

    'image/pjpeg',

    'image/gif',

    'image/bmp',

    'image/x-png'

);

 

$max_file_size=2000000;     //上传文件大小限制, 单位BYTE

$destination_folder="../uploadimg/"; //上传文件路径

?>

<html>

<head>

<title>添加上传图片</title>

<style type="text/css">

<!--

body

{

   font-size: 12px;

 margin:0px;

}

input, select, textarea { border:1px solid #CCC; font-size:12px; padding:2px; font-family:"宋体"; }

-->

</style>

</head>

 

<body>

<form enctype="multipart/form-data" method="post" name="upform">

  <input name="upfile" type="file" size="30">

  <input type="submit" value="上传"><br>

  <span style="font-size:13px; color:#F00;">

  允许上传的文件类型为:jpg, jpeg, png, pjpeg, gif, bmp, x-png</span>

</form>

 

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')

{

    if (!is_uploaded_file($_FILES["upfile"][tmp_name]))

    //是否存在文件

    {

         echo "图片不存在!";

         exit;

    }

 

    $file = $_FILES["upfile"];

    if($max_file_size < $file["size"])

    //检查文件大小

    {

        echo "文件太大!";

        exit;

    }

 

    if(!in_array($file["type"], $uptypes))

    //检查文件类型

    {

        echo "文件类型不符!".$file["type"];

        exit;

    }

 

    if(!file_exists($destination_folder))

    {

        mkdir($destination_folder);

    }

 

    $filename=$file["tmp_name"];

    $image_size = getimagesize($filename);

    $pinfo=pathinfo($file["name"]);

    $ftype=$pinfo['extension'];

    $destination = $destination_folder.time().".".$ftype;

    if (file_exists($destination) && $overwrite != true)

    {

        echo "同名文件已经存在了";

        exit;

    }

 

    if(!move_uploaded_file ($filename, $destination))

    {

        echo "移动文件出错";

        exit;

    }

 

    $pinfo=pathinfo($destination);

    $fname=$pinfo[basename];

?>

    <script type ="text/javascript">

<?php

if(isset($_GET['label'])){//如果是批量上传?>

window.parent.document.getElementByIdx_x_x("pic_name<?php echo $_GET['label']?>").value = "<?php echo $file["name"]?>";

window.parent.document.getElementByIdx_x_x("pic_url<?php echo $_GET['label']?>").value = 'uploadimg/<?php echo $fname?>';

window.parent.document.getElementByIdx_x_x('light').style.display='none';

window.parent.document.getElementByIdx_x_x('fade').style.display='none';

window.close();

<?php }

else{?>

window.parent.document.thisform.uploadfile.value='uploadimg/<?=$fname?>';

window.parent.document.getElementByIdx_x_x("success").innerHTML=("上传成功! 宽度:<?=$image_size[0]?>px 长度:<?=$image_size[1]?>px  大小:<?=$file["size"].' '.bytes?>");

 

<?php }?>

 </script>

    <?

}

?>

</body>

完成,当然,在保存图片的时候可以自己添加保存缩略图的代码,具体自己扩展,仅供参考

参考文章:http://blog.ncmem.com/wordpress/2023/11/11/php-%e6%89%b9%e9%87%8f%e4%b8%8a%e4%bc%a0%e6%96%87%e4%bb%b6-%e5%a4%a7%e5%85%a8/
欢迎入群一起讨论

在这里插入图片描述