php文件上传与下载(附封装好的函数文件)
发布时间:2020-12-13 20:55:18 所属栏目:PHP教程 来源:网络整理
导读:单文件上传 前端页面 ! DOCTYPE html html lang ="en" head meta charset ="UTF-8" title Upload A File / body form action ="upload.php" method ="post" enctype ="multipart/form-data" input type ="hidden" name ="MAX_FILE_SIZE" value ="1024000" /
单文件上传 <!DOCTYPE html> <html lang="en"head> meta charset="UTF-8"title>Upload A File</bodyform action="upload.php" method="post" enctype="multipart/form-data"> input type="hidden" name="MAX_FILE_SIZE" value="1024000" /> ="file"="test_pic" ="submit"="上传" /> formhtml> 后端实现upload.php <?php /** * Created by PhpStorm. * Date: 2018/11/11 * Time: 14:06 */ // 接收$_FILES数组 $key = 'test_pic'; $mimeWhiteList = ['image/jpeg','image/png','image/gif'];文件映射白名单 $extWhiteList = ['jpeg','jpg','png','gif'];文件扩展名白名单 $allowSize = 2*1024*1024$destDir = './uploads'; $name = $_FILES[$key]['name']; 源文件名称 $type = $key]['type']; MIME 类型 $tmpName = $key]['tmp_name']; 临时文件名称 $error = $key]['error']; 错误信息 $size = $key]['size']; 文件大小 字节 // 处理错误 // 0 - 无错误 if ($error > UPLOAD_ERR_OK) { switch($error) { 1 - 文件大小超出了php.ini当中的upload_max_filesize的大小 case UPLOAD_ERR_INI_SIZE: exit('文件大小超出了php.ini当中的upload_max_filesize的大小'); 2 - 超出表单当中的MAX_FILE_SIZE的大小 case UPLOAD_ERR_FORM_SIZE: exit('超出表单当中的MAX_FILE_SIZE的大小' 3 - 部分文件被上传 case UPLOAD_ERR_PARTIAL: exit('部分文件被上传' 4 - 没有文件被上传 case UPLOAD_ERR_NO_FILE: exit('没有文件被上传' 6 - 临时目录不存在 case UPLOAD_ERR_NO_TMP_DIR: exit('临时目录不存在' 7 - 磁盘写入失败 case UPLOAD_ERR_CANT_WRITE: exit('磁盘写入失败' 8 - 文件上传被PHP扩展阻止 case UPLOAD_ERR_EXTENSION: exit('文件上传被PHP扩展阻止'default: exit('未知错误'); } } 限制文件的MIME if (!in_array($type,$mimeWhiteList)) { exit('文件类型' . $type . '不被允许!'); } 限制文件的扩展名 $ext = pathinfo($name, PATHINFO_EXTENSION); $ext,1)">$extWhiteListexit('文件扩展名' . $ext . '不被允许!' 限制文件大小 $size > $allowSize) { exit('文件大小 ' . $size . ' 超出限定大小 ' . $allowSize . ' !' 生成新的随机文件名称 // md5(rand()); $fileName = uniqid() . '.' . $ext; 移动临时文件到指定目录当中并重新命名文件名 file_exists($destDirmkdir($destDir,0777,1)">true); } if (is_uploaded_file($tmpName) && move_uploaded_file($tmpName,1)">$destDir . '/' . $fileNameecho "恭喜,文件上传成功"; } else { echo "很抱歉,文件上传失败"; } 多文件上传,指定文件数量 >Upload Multiple Files="multiple_upload.php"="test_pic1" ="test_pic2" ="test_pic3" /> > 后端实现multiple_upload.php <?* * Created by PhpStorm. * Date: 2018/11/11 * Time: 14:54 */ $errors = []; ]; foreach($_FILES as $key => $val name type tmp_name error size // 接收$_FILES 源文件名称 MIME 类型 临时文件名称 错误信息 文件大小 字节 // 处理错误 // 0 - 无错误 UPLOAD_ERR_OK) { ) { 1 - 文件大小超出了php.ini当中的upload_max_filesize的大小 case UPLOAD_ERR_INI_SIZE: $errors[$key] = '文件大小超出了php.ini当中的upload_max_filesize的大小'; continue 2; 2 - 超出表单当中的MAX_FILE_SIZE的大小 case UPLOAD_ERR_FORM_SIZE: $key] = '超出表单当中的MAX_FILE_SIZE的大小' 3 - 部分文件被上传 case UPLOAD_ERR_PARTIAL: $key] = '部分文件被上传' 4 - 没有文件被上传 case UPLOAD_ERR_NO_FILE: $key] = '没有文件被上传' 6 - 临时目录不存在 case UPLOAD_ERR_NO_TMP_DIR: $key] = '临时目录不存在' 7 - 磁盘写入失败 case UPLOAD_ERR_CANT_WRITE: $key] = '磁盘写入失败' 8 - 文件上传被PHP扩展阻止 case UPLOAD_ERR_EXTENSION: $key] = '文件上传被PHP扩展阻止'default: $key] = '未知错误'; } } 限制MIME )) { $key] = '文件类型' . ; continue; } 限制扩展名 PATHINFO_EXTENSION); $key] = '文件扩展名' . 限制大小 ) { $key] = '文件大小 ' . 生成随机文件名称 ; 移动文件 )) { ); } $tmpName) || !$key] = "很抱歉,文件上传失败"; } } count($errors) > 0var_dump($errors); } echo "文件全部上传成功"; } 多文件上传,不定文件数量 ="multiple_upload2.php"="6024000" ="test_pic[]" > 后端实现multiple_upload2.php <?* * Created by PhpStorm. * Date: 2018/11/11 * Time: 15:12 接收和处理$_FILES empty($key])) { $files = []; $key]['name'] $k => $v$files[$k]['name'] = ; $k]['type'] = $key]['type'][$k]; $k]['tmp_name'] = $key]['tmp_name'][$k]['error'] = $key]['error'][$k]['size'] = $key]['size'][]; } } []; $files $file name type error size $file['name']; $file['type']; $file['tmp_name']; $file['error']; $file['size']; $key] = $name . '文件大小超出了php.ini当中的upload_max_filesize的大小'$key] = $name . '超出表单当中的MAX_FILE_SIZE的大小'$name . '部分文件被上传'$name . '没有文件被上传'$name . '临时目录不存在'$name . '磁盘写入失败'$name . '文件上传被PHP扩展阻止'$name . '未知错误' 限制MIME类型 限制文件大小 ; } 文件上传类封装 UploadFile.php <?* * Created by PhpStorm. * Date: 2018/11/11 * Time: 22:01 class UploadFile { * * */ const UPLOAD_ERROR = [ UPLOAD_ERR_INI_SIZE => '文件大小超出了php.ini当中的upload_max_filesize的值',1)"> UPLOAD_ERR_FORM_SIZE => '文件大小超出了MAX_FILE_SIZE的值',1)"> UPLOAD_ERR_PARTIAL => '文件只有部分被上传',1)"> UPLOAD_ERR_NO_FILE => '没有文件被上传',1)"> UPLOAD_ERR_NO_TMP_DIR => '找不到临时目录',1)"> UPLOAD_ERR_CANT_WRITE => '写入磁盘失败',1)"> UPLOAD_ERR_EXTENSION => '文件上传被扩展阻止',1)"> ]; * * @var protected $field_name* * @var string $destination_dir* * @var array $allow_mime$allow_ext$file_org_name$file_type$file_tmp_name$file_error$file_size$extension$file_new_name* * @var float|int $allow_size* * UploadFile constructor. * @param $keyName * @param string $destinationDir * @param array $allowMime * @param array $allowExt * @param float|int $allowSize public function __construct($keyName,1)">$destinationDir = './uploads',1)">$allowMime = ['image/jpeg','image/gif'],1)">$allowExt = ['gif','jpeg'],1)">) { $this->field_name = $keyName$this->destination_dir = $destinationDir$this->allow_mime = $allowMime$this->allow_ext = $allowExt$this->allow_size = * * @param $destinationDir function setDestinationDir(* * @param $allowMime function setAllowMime(* * @param $allowExt function setAllowExt(* * @param $allowSize function setAllowSize(* * @return bool function upload() { 判断是否为多文件上传 []; is_array($this->field_name]['name'])) { $this->field_name]['name'] ) { ; $this->field_name]['type'][]; $this->field_name]['tmp_name'][$this->field_name]['error'][$this->field_name]['size'][]; } } { $files[] = $this->field_name]; } 接收$_FILES参数 $this->setFileInfo($key,1)">); 检查错误 $this->checkError( 检查MIME类型 $this->checkMime( 检查扩展名 $this->checkExt( 检查文件大小 $this->checkSize( 生成新的文件名称 $this->generateNewName(count((array)$this->getError($key)) > 0) { ; } 移动文件 $this->moveFile(); } $this->errors) > 0return false; } * * @return array getErrors() { return errors; } * * @param $key * @return mixed protected function getError() { $this->errors[]; } function setFileInfo( $_FILES name type temp_name error size $this->file_org_name[$file['name'$this->file_type[$file['type'$this->file_tmp_name[$file['tmp_name'$this->file_error[$file['error'$this->file_size[$file['size']; } * * @param $key * @param $error function setError($key][] = ; } * * @param $key * @return bool function checkError($this->file_error > UPLOAD_ERR_OK) { file_error) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: $this->setError(file_error]); ; } } function checkMime($key],1)">allow_mime)) { $key] . '不被允许!'); function checkExt($this->extension[$key] = PATHINFO_EXTENSION); allow_ext)) { $key] . '不被允许!'function checkSize($key] > allow_size) { $key] . '超出了限定大小' . allow_size); * * @param $key function generateNewName($this->file_new_name[function moveFile(destination_dir)) { $this->destination_dir,1)">); } $newName = rtrim(]; $key]) && $newName)) { ; } * * @return mixed getFileName() { file_new_name; } * * @return string getDestinationDir() { destination_dir; } getExtension() { extension; } getFileSize() { file_size; } } 前端页面演示 >Test Upload Class="TestUploadFile.php"="10240000" ="test_pic[]" multiple="multiple"> 后端配置演示TestUploadFile.php? <?* * Created by PhpStorm. * Date: 2018/11/11 * Time: 22:46 */ require('UploadFile.php'); $upload = new UploadFile('test_pic'); $upload->setDestinationDir('./uploads'$upload->setAllowMime(['image/jpeg',1)">]); $upload->setAllowExt(['gif','jpeg'$upload->setAllowSize(2*1024*1024); $upload->upload()) { getFileName()); getDestinationDir()); getExtension()); getFileSize()); } getErrors()); } 文件下载 <?* * Created by PhpStorm. * Date: 2018/11/12 * Time: 00:07 演示 //echo '<a href="./uploads/test.jpg">下载图片</a>'; // download.php?file=5be822d84c42a.jpeg // 接收get参数 isset($_GET['file'])) { exit('需要传递文件名称'exit('请传递文件名称' 获取远程文件地址 $file = './uploads/' . ]; exit('文件不存在'is_file(is_readable(exit('文件不可读' 清空缓冲区 ob_clean(); 打开文件 rb $file_handle = fopen($file,'rb'); if (!$file_handleexit('打开文件失败' 通知浏览器 header('Content-type: application/octet-stream; charset=utf-8'header('Content-Transfer-Encoding: binary'header('Content-Length: ' . filesize()); header('Content-Disposition: attachment; filename="' . urlencode(basename($file)) . '"' 读取并输出文件 while(!feof(echo fread($file_handle,10240 关闭文档流 fclose($file_handle); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |