文件的上传和下载封装方法

Original 2019-03-31 17:15:37 1016
abstract://上传方法 /**  * 单文件上传操作  * @param $fileInfo      // 上传的文件信息  * @param string $uploadPath  //  上传的指定目录
//上传方法
/**
 * 单文件上传操作
 * @param $fileInfo      // 上传的文件信息
 * @param string $uploadPath  //  上传的指定目录
 * @param array $allowExt  // 上传的文件类型
 * @param int $maxSize   // 上传的最大值
 * @return string      提示信息
 */
function upload_file($fileInfo,$uploadPath='./upload',$allowExt=['png','jpg','jpeg','gif','txt','html'],$maxSize = 1000000)
{
    // 判断上传错误号
    if($fileInfo['error'] === 0){
        // 获取文件后缀
      $ext = strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION));
        // 判断文件类型
      if (!in_array($ext,$allowExt)){
          return '非法文件类型!';
      }
        // 判断文件大小
      if ($fileInfo['size']>$maxSize){
          return '超出文件上传的最大值';
      }
        // 判断文件上传方式
      if (!is_uploaded_file($fileInfo['tmp_name'])){
          return '非法上传!';
      }
        // 判断需要移动到的目录是否存在
      if(!is_dir($uploadPath)){
          mkdir($uploadPath,0777,true);
      }
        // 生成唯一的文件名 uniqid 生成唯一id microtime 返回当前unix时间戳中的微妙
      $uniName = md5(uniqid(microtime(),true)).".".$ext;
        // 拼接路径以及文件名
      $dast = $uploadPath."/".$uniName;
        // 将文件移动到指定目录
      if (!move_uploaded_file($fileInfo['tmp_name'],$dast)){
          return '文件上传失败!';
      }
      return '文件上传成功!';
    }else{
        switch ($fileInfo['error']){
            case 1:
                $res = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值!';
                break;
            case 2:
                $res = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值!';
                break;
            case 3:
                $res = '文件只有部分被上传!';
                break;
            case 4:
                $res = '没有文件被上传!';
                break;
            case 6:
            case 7:
                $res = '系统错误!';
                break;
        }
        return $res;
    }
}
//html上传页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="MyFile">
    <input type="submit" value="上传">
</form>
</body>
</html>
//upload.php
<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2019/3/31
 * Time: 16:21
 */
include 'function.php';
$fileInfo = $_FILES['MyFile'];
var_dump(upload_file($fileInfo));

QQ图片20190331171309.png

//下载操作
/**
 * 文件下载操作
 * @param $filename // 需要下载的文件名
 */
function dow_file($filename)
{
    // 告诉浏览器返回文件的大小
    header('Accept-Length:'.filesize($filename));
    // 告诉浏览器文件作为复件处理,并告诉浏览器下载完的文件名
    header('Content-Disposition:attachment;filename='.basename($filename));
    // 输出文件
    readfile($filename);
}
dow_file('6.jpg');


Correcting teacher:查无此人Correction time:2019-04-01 09:54:59
Teacher's summary:完成的不错。上传一定要把文件类型给判断了。不能让其他类型的文件也上传。

Release Notes

Popular Entries