完成简单的文件上传/下载功能的页面

Original 2019-04-17 14:03:25 294
abstract:<!doctype html> <html> <head>     <meta charset="UTF-8">     <meta name="viewport"   &nb
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>文件上传/下载页面</title>
</head>
<body>
        <form action="upFile.php" method="post" enctype="multipart/form-data" >
          <label>请选择需要上传的文件:</label>  <input type="file" name = "upFile"> <br><br>
            <label> 请确定开始上传此文件:</label>  <input type="submit" value="上传">
        </form>
        <br><br>
        <form action="down.php" method="get">
            <input type="text" name="downFileName" value="demo.rar">
            <input type="submit" value="下载">
        </form>
</body>
</html>
//upFile.php
<?php
    require 'upFun.php';
    print_r(upFile($_FILES['upFile']));
?>
//down.php
<?php
require 'upFun.php';
$downFile=$_GET['downFileName'];
dowFile($downFile);
?>
//upFun.php
<?php
function dowFile($fileName)
{
    header('Accept-Length:'.filesize($fileName));
//  主要是这一行
    header('Content-Disposition:attachment;filename='.basename($fileName));
    readfile($fileName);
}

function upFile($fileInfo,$uploadPath='./upload',$allowExt = ['png','jpg','jpeg','gif'
    ,'txt','html'],$maxSize = 2000000){
    if($fileInfo['error'] ===0){
        //返回文件后缀名
        $ext = strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION));
        if(!in_array($ext,$allowExt)){
            return '非法文件类型';
        }
        if(!is_uploaded_file($fileInfo['tmp_name'])){
            return '非法上传!';
        }
        if(!is_dir($uploadPath)){
            mkdir($uploadPath,0777,true);
        }
        //文件名,用md生成的
        $uniName = md5(uniqid(microtime(true),true)).".".$ext;
        //新文件名
        $dest = $uploadPath."/".$uniName;

        if(!move_uploaded_file($fileInfo['tmp_name'],$dest))
        {
            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;
    }
}

20190417140213.jpg


Correcting teacher:查无此人Correction time:2019-04-18 09:53:49
Teacher's summary:完成的不错,上传文件格式记得要限制一下。不然会有病毒上传。继续加油。

Release Notes

Popular Entries