返回文件上传、下载......登陆

文件上传、下载方法封装

蓦然回首2019-02-23 11:16:23313

<?php

<form action="upload.php" method="post" enctype="multipart/form-data">

    <input type="file" name="Myfile">

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

    </form>

/**

 * 文件下载操作

 * $filename 需要下载的文件名

 */

function dow_file($filename){

//告诉浏览器告诉返回文件的大小

header('Accept-Length:'.filesize($filename));

//告诉浏览器,文件作为附件处理,并告诉浏览器下载完的文件名

header('Countent-Disposition:attachment;filename=',basename($filename));

//输出文件

readfile($filename);

}



/**

 * $fileInfo 上传的文件信息

 * $uploadPath 上传的指定目录

 * $allowExt 上传的文件类型

 * $maxSize 上传文件的最大值(字节)

 */

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_EXTENESION));

//判断文件类型

if(!in_array($ext, $allowExt)){

return '非法文件类型';

}

//判断文件大小

if($fileInfo['size'] > $maxSize){

return '超出允许上传的最大值!';

}

//判断文件上传方式

if(!is_uploaded_file($fileInfo['name'])){

return '非法上传操作';

}

//判断目录是否存在,不存在则创建

if(!is_dir($uploadPath)){

mkdir($uploadPath,0777,true);

}

//生成唯一文件名,uniqid生成唯一id,microtime返回当前unix时间戳中的微秒

$uniName = md5(uniqid(microtime(true),true)).'.'.$allowExt;

//拼接路径以及文件名

$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:

$res = '找不到临时文件夹。';

break;


case 7:

$res = '文件写入失败。';

break;

}

return $res;

}

}

$fileinfo = $_FILES['Myfile'];

if($fileinfo){

    upload_file($fileinfo);

}

?>


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送