php上传文件代码解析

思想;把html的input标签组织成一个数组,而后去重php

关键技术涉及的函数 is_dir mkdir move_uploaded_file()html

涉及的数组 预约义数组$_FILES数组

步骤一:检查上传文件夹是否存在,若是不存在就建立(注意!尽可能使用绝对路径,不然可能上传失败)函数

$targetdir = "H:\\myphpproject\\myPHP\\upresource"; if (!is_dir($targetdir)){ mkdir($targetdir); }

step2: 把html的input标签组织为数组,关键在于name属性要起作 xxxx[]的形式post

 <form method="post" action="upfile.php" enctype="multipart/form-data">
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <br/>
            <button type="submit" class="btn btn-success">提交</button>  
 </form>       

step3:对上传文件去重,并组织上传文件的数组; 关键技术 array_unique编码

$arrayfile = array_unique($_FILES['myfile']['name']);

step4:循环遍历input标签得到文件名,并和目标文件夹路径组成上传文件的绝对路径spa

 $path = $targetdir."\\".$v;

step5:循环遍历每一个input标签,上传文件 关键技术:foreach ($arrayfile as $k=>$v);上传用到 move_uploaded_file($_FILES[标签数组名][‘tmp_name’][数组索引],$v),其中tmp_name是固定用法,没必要深究;$v是上传成功后,文件的绝对路径名rest

$res是判断上传结果的布尔型变量code

foreach($arrayfile as $k=>$v) { $path = $targetdir."\\".$v; if ($v) { if(move_uploaded_file($_FILES['myfile']['tmp_name'][$k],$path)) { $res = TRUE; } else { $res=FALSE; } } }

总体既视感以下orm

html上传文件部分  ----input标签 type要设置成 file, enctype="multipart/form-data"不能省略

  <form method="post" action="upfile.php" enctype="multipart/form-data">
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <div class="media text-muted pt-3">
              <input type="file" class="form-control" name="myfile[]" aria-label="Amount (to the nearest dollar)">
            </div>
            <br/>
            <button type="submit" class="btn btn-success">提交</button>  
  </form>       

整个上传文件控制编码部分

<?php $targetdir = "H:\\myphpproject\\myPHP\\upresource"; if (!is_dir($targetdir)){ mkdir($targetdir); } $arrayfile = array_unique($_FILES['myfile']['name']); $res = FALSE; foreach($arrayfile as $k=>$v) { $path = $targetdir."\\".$v; if ($v) { if(move_uploaded_file($_FILES['myfile']['tmp_name'][$k],$path)) { $res = TRUE; } else { $res=FALSE; } } } if ($res==TRUE) { echo "文件上传成功"; } else { echo "文件上传失败"; } ?>
相关文章
相关标签/搜索