>  기사  >  백엔드 개발  >  PHP 파일 업로드, 다운로드 및 삭제 예제

PHP 파일 업로드, 다운로드 및 삭제 예제

高洛峰
高洛峰원래의
2017-01-06 14:57:101344검색

PHP 파일 업로드, 다운로드, 삭제 예제의 일반적인 개념은 다음과 같으며, 구체적인 내용은 다음과 같습니다

1. 파일 업로드

1. 파일 업로드 영역을 만듭니다.
div1

2. 파일을 표시할 영역을 만듭니다.
div2

3. 파일

4. 서버 파일 데이터 수신
$_FILE[name]을 사용하여 수신

5. 업로드된 파일에 오류가 있는지 확인합니다.

오류는 다음과 같습니다.
1) 업로드된 파일이 php.ini의 upload_max_filesize 옵션에 의해 제한되는 값을 초과합니다
2). HTML 형식의 MAX_FILE_SIZE 옵션에 지정된 값
3) 파일의 일부만 업로드되었습니다.
4) 업로드된 파일이 없습니다
5) 파일이 없습니다. 쓰기 실패

6. 업로드된 파일을 임시 폴더에서 지정된 폴더 저장소로 이동

이 move_uploaded_file 함수를 사용하세요
4, 5, 6단계를 함수로 만들어 직접 호출할 수 있습니다.
참고: 파일 업로드 페이지에 PHP 코드를 포함해야 하는 경우 파일 확장자는 html일 수 없지만 .php

2. 파일 다운로드


1. 파일 이름을 서버에 전송

2. 서버는 파일 이름을 받은 다음 파일에 경로를 추가합니다.

3. 그런 다음 파일 데이터를 클라이언트에 다시 전송합니다


일반적으로 다음 네 단계는 다음과 같습니다.

//1.重设响应类型
$info = getimagesize($rootPath.$file);
header("Content-Type:".$info['mime']);
//2.执行下载的文件名
header("Content-Disposition:attachment;filename=".$file);
//3.指定文件大小
header("Content-Length:".filesize($rootPath.$file));
//4.响应内容
readfile($rootPath.$file);

3. 파일 삭제


1. 파일 이름을 서버에

2. 서버가 파일 이름을 받은 후 파일의 경로를 추가합니다.

3. 파일을 삭제하려면 연결 해제 기능을 사용하세요

다음은 이미지 업로드, 다운로드 및 삭제에 대한 간단한 예입니다.

효과는 다음과 같습니다.

PHP 파일 업로드, 다운로드 및 삭제 예제

파일 업로드, 다운로드 및 삭제를 위한 인터페이스, 코드는 다음과 같습니다.

html+php 임베디드:

<!-- 选择上传文件区域-->
<div id="div1">
  <form action="upLoadFile.php" method="post" enctype="multipart/form-data">
    <div id="div2"><input type="text" id="show" /></div>
    <div id="div3">
      <span class="text">选择文件</span>
       <input type=&#39;hidden&#39; name=&#39;MAX_FILE_SIZE&#39; value=&#39;100000000&#39;> <!--表单上传文件的大小限制<100M,也可以设置其它值-->
      <input type="file" id="upfile" name="file" />
    </div>
    <input type="submit" value="上传" class="upload" />
  </form>
</div>
<!-- 选择上传文件区域结束-->
 
<!-- 上传文件显示区域-->
<div id="show-file">
  <ul id="ul-list">
    <!-- 内嵌php代码,为了动态显示上传的文件-->
    <?php
    //1.打开目录
    $dir = opendir(&#39;upload&#39;);
    //2.遍历目录
    $i = 0;
    while($file = readdir($dir))
    {
      if($file == &#39;.&#39;||$file == &#39;..&#39;)
        continue;
      echo "<li><img  src=&#39;upload/{$file}&#39;    style="max-width:90%"PHP 파일 업로드, 다운로드 및 삭제 예제" >
        <div><a href=&#39;deleteFile.php?name={$file}&#39;>删除</a></span></div>
        <span><a href=&#39;download.php?name={$file}&#39;>下载</a></span></li>";
    }
    //3.关闭目录
    closedir($dir);
    ?>
    <!-- 内嵌php代码结束-->
  </ul>
</div>
<!-- 上传文件显示区域结束-->
css 코드:

*{margin:0;padding:0;}
    ul,li{list-style: none;}
    /*最外层的div,目的是包住选择文件按钮,显示框和上传文件按钮*/
    #div1{width:405px;height:38px;position: relative;margin:40px auto;}
 
    /*第二层div包住显示框和上传按钮,右浮动*/
    #div2{float: right;}
    #div2 input {width:250px;height: 38px;font-size: 22px;}
 
    /*第三层div包住input file*/
    #div3{float:left;width:140px;height:38px;position: relative;
      background: url("upload.jpg") no-repeat 0 0;margin-left: 5px;}
    #div3 input{position: absolute;width:100%;height: 100%;top:0;left: 0;
      z-index: 1;opacity:0;}
 
    /*图片(选择文件按钮)上的文字*/
    .text{display: block;width:140px;height: 38px;position: absolute;top: 0;
      left:0;text-align: center;line-height: 38px;font-size: 28px;
      color: orchid;}
 
    /*上传按钮的位置*/
    .upload{width:70px;height: 38px;background: greenyellow;position: absolute;top:0;right: -75px;}
 
    /*鼠标停留在选择文件按钮上的时候切换图片*/
    #div3:hover{background: url("upload.jpg") no-repeat 0 -40px;}
 
    /*显示图片的div->ul,采用左浮动的方式,一行行的排列图片*/
    #show-file{width:760px;height:445px;position: relative;margin:10px auto;overflow: scroll;}
    #show-file ul{width:760px;height:445px;position: absolute;top:0;left:0;}
    #show-file ul li{float: left;width:120px;height: 100px;margin: 3px 0 0 3px;position: relative;}
 
    /*删除按钮的位置和一些样式*/
    #show-file ul li div{display: none;opacity: 0;width:40px;height: 20px;position: absolute;left: 5px;bottom: 5px;
      background: gold;color: #d32a0e;z-index: 1;cursor: pointer;text-align: center;line-height: 20px;}
 
    /*下载按钮的位置和一些样式*/
    #show-file ul li span{display: none;opacity: 0;width:40px;height: 20px;position: absolute;right: 5px;bottom: 5px;
      background: gold;color: #d32a0e;z-index: 1;cursor: pointer;text-align: center;line-height: 20px;}
 
    /*把a标签的自带样式去掉,鼠标停留时字体换颜色*/
    #show-file ul li span,div a{text-decoration: none;color:orangered;}
    #show-file ul li span,div a:hover{color: #00fa00;}
js 코드:

<script src="move.js"></script>
 <script>
   window.onload = function ()
   {
     //当选择文件后,会触发这个事件
     $(&#39;upfile&#39;).onchange = function ()
     {
       $(&#39;show&#39;).value = this.value;//把获取到的文件伪路径传到编辑框
     };
     //显示下载按钮
     var aLi = $(&#39;ul-list&#39;).getElementsByTagName(&#39;li&#39;);   //图片
     var aSpan = $(&#39;ul-list&#39;).getElementsByTagName(&#39;span&#39;); //下载按钮
     var aDiv = $(&#39;ul-list&#39;).getElementsByTagName(&#39;div&#39;);  //删除按钮
     for(var i = 0;i<aLi.length;i++)
     {
       aLi[i].index = i;
       aLi[i].onmousemove = function ()
       {
         aSpan[this.index].style.display = &#39;block&#39;;
         aDiv[this.index].style.display = &#39;block&#39;;
         startMove(aDiv[this.index],{opacity:100}); //缓冲运动
         startMove(aSpan[this.index],{opacity:100}); //缓冲运动
       };
       aLi[i].onmouseout = function ()
       {
         aSpan[this.index].style.display = &#39;none&#39;;
         aDiv[this.index].style.display = &#39;none&#39;;
         startMove(aDiv[this.index],{opacity:0});  //缓冲运动
         startMove(aSpan[this.index],{opacity:0});  //缓冲运动
       }
     }
   };
   function $(id)
   {
     return document.getElementById(id);
   }
 </script>
업로드된 파일 처리를 위한 PHP 파일 :

include(&#39;myFunctions.php&#39;);
if(uploadFile(&#39;file&#39;,&#39;upload&#39;))
  header("Location:upFileAndDownFile.php");//会马上跳转回原页面,根本感觉不到页面有跳转到这里
다운로드한 파일 처리용 PHP 파일:

include(&#39;myFunctions.php&#39;);
//获取要下载的文件名(加上路径)
$file = $_GET[&#39;name&#39;];
$rootPath = &#39;upload/&#39;;
downLoadFile($file,$rootPath);
 
处理删除文件的php文件:
 
$fileName = &#39;upload/&#39;.$_GET[&#39;name&#39;];
unlink($fileName);
header("Location:upFileAndDownFile.php");
 
其中move.js在前面的JS完美运动框架文章有讲过。 
myFunctions.php中的函数如下:
 
/**
 * @function 下载文件
 * @param $file 要下载的文件名
 * @param $rootPath 文件根路径
 * @return 无
 */
function downLoadFile($file,$rootPath)
{
  //1.重设响应类型
  $info = getimagesize($rootPath.$file);
  header("Content-Type:".$info[&#39;mime&#39;]);
  //2.执行下载的文件名
  header("Content-Disposition:attachment;filename=".$file);
  //3.指定文件大小
  header("Content-Length:".filesize($rootPath.$file));
  //4.响应内容
  readfile($rootPath.$file);
}
 
 
/**
 * @function 上传文件
 * @param $name 表单名 <input type="file" name="pic" />
 * @param $path 上传后,文件存放的路径
 * @return 返回新的文件路径表示上传成功 false 失败
 */
function uploadFile($name,$path)
{
  $file = $_FILES[$name];
  //1.过滤上传文件的错误号
  if($file[&#39;error&#39;] > 0)
  {
    //获取错误信息
    switch($file[&#39;error&#39;])
    {
      case 1:
        $info = &#39;上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。&#39;;
        break;
      case 2:
        $info = &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。&#39;;
        break;
      case 3:
        $info = &#39;文件只有部分被上传。&#39;;
        break;
      case 4:
        $info = &#39;没有文件被上传。&#39;;
        break;
      case 6:
        $info = &#39;找不到临时文件夹&#39;;
        break;
      case 7:
        $info = &#39;文件写入失败。 &#39;;
        break;
    }
    die("上传错误,原因: ".$info);
  }
  //2.上传文件大小的过滤
  if($file[&#39;size&#39;] > 100000000)  //字节为单位
    die(&#39;上传文件大小超出限制!&#39;);
  //3.上传后的文件名定义
  $newfile = null;
  $fileinfo = pathinfo($file[&#39;name&#39;]); //解析上传文件名
  do{
    $newfile = date(&#39;YmdHis&#39;).".".$fileinfo[&#39;extension&#39;];
  }while(file_exists($path.&#39;/&#39;.$newfile));
  //4.执行文件上传
  //判断是否是一个上传文件
  if(is_uploaded_file($file[&#39;tmp_name&#39;]))
  {
    //执行文件上传(移动文件到指定目录)
    if(move_uploaded_file($file[&#39;tmp_name&#39;],$path.&#39;/&#39;.$newfile))
      return $path.&#39;/&#39;.$newfile;
    else
      return false;
  }
  else
    die(&#39;不是一个上传文件!&#39;);
}
파일 업로드 시 HTML 양식의 크기 제한과 서버 크기 제한, 게시물 크기 제한을 반드시 설정하세요. .

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다.

PHP 파일 업로드, 다운로드, 삭제 예제와 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.