PHP 实现网页文件上传 及 文件展示

2023-10-10 08:20

本文主要是介绍PHP 实现网页文件上传 及 文件展示,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

效果展示

部分内容及实现代码

文件上传

发送数据到当前页面  并使用php处理

 当提交空白表单时 需要用js提前处理 不进行提交

提交过后判断文件格式是否接受

展示文件

 获取文件地址

 开始展示文件

美化或优化

完整代码



效果展示

 

没学过php  其中php内容全靠复制粘贴

创建./upload  文件夹 用来存储文件

用到的技术(一点即可)

html      css       javascript       php



部分内容及实现代码



文件上传

参考:PHP 文件上传 | 菜鸟教程 (runoob.com)

文件上传参考菜鸟教程    其中也有改变的地方

发送数据到当前页面  并使用php处理

<form action="form.php" method="post" onsubmit="return checkinput();" enctype="multipart/form-data"><input type="file" name="file" id="file"><input type="submit" class="submit"  onclick="validate()" name="submit" value="上  传">
</form>

 当提交空白表单时 需要用js提前处理 不进行提交

            <script>var a = true;function validate(){var file = document.getElementById("file").value;if(file==""){const int = document.querySelector(".submit");int.style.backgroundColor="red";int.style.fontSize = "25px";int.value = "失  败"function move(){int.style.backgroundColor="#00a1d6";int.value = "上  传"int.style.fontSize = "16px";}setTimeout(move,2000);a=false;return;}else{a=true;}}function checkinput(){return a;}</script>



提交过后判断文件格式是否接受

if($_SERVER["REQUEST_METHOD"] == "POST" && empty($_POST["file"]) !== false){$allowedExts = array("gif", "jpeg", "jpg", "png","zip","rar","tar",'tgz',"txt","xml","html","css","js");$temp = explode(".", $_FILES["file"]["name"]);// echo $_FILES["file"]["size"];$extension = end($temp);     // 获取文件后缀名if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/jpg")|| ($_FILES["file"]["type"] == "image/pjpeg")|| ($_FILES["file"]["type"] == "image/x-png")|| ($_FILES["file"]["type"] == "image/png")|| ($_FILES["file"]["type"] == "application/octet-stream")|| ($_FILES["file"]["type"] == "application/x-tar")|| ($_FILES["file"]["type"] == "application/x-compressed")|| ($_FILES["file"]["type"] == "application/x-zip-compressed")|| ($_FILES["file"]["type"] == "text/plain")|| ($_FILES["file"]["type"] == "text/xml")|| ($_FILES["file"]["type"] == "text/html")|| ($_FILES["file"]["type"] == "text/css")|| ($_FILES["file"]["type"] == "text/javascript"))&& ($_FILES["file"]["size"] < 20480000)   && in_array($extension, $allowedExts)){if ($_FILES["file"]["error"] > 0){echo "错误:: " . $_FILES["file"]["error"] . "<br>";}else{echo '<script>const int = document.querySelector(".submit");int.style.backgroundColor="gold";int.style.fontSize = "25px";int.value = "成  功"function move(){location = "原来的网址";}setTimeout(move,2000);</script>';move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);}}else{echo '<script>const int = document.querySelector(".submit");int.style.backgroundColor="red";int.style.fontSize = "25px";int.value = "失  败"function move(){location = "原来的网址";}setTimeout(move,1000);</script>';}}


常见文件类型

常用的MIME类型
.doc     application/msword
.docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf       application/rtf
.xls     application/vnd.ms-excel application/x-excel
.xlsx    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt     application/vnd.ms-powerpoint
.pptx    application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps     application/vnd.ms-powerpoint
.ppsx   application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf     application/pdf
.swf    application/x-shockwave-flash
.dll      application/x-msdownload
.exe    application/octet-stream
.msi    application/octet-stream
.chm    application/octet-stream
.cab    application/octet-stream
.ocx    application/octet-stream
.rar     application/octet-stream
.tar     application/x-tar
.tgz    application/x-compressed
.zip    application/x-zip-compressed
.z       application/x-compress
.wav   audio/wav
.wma   audio/x-ms-wma
.wmv   video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg     audio/mpeg
.rm     application/vnd.rn-realmedia
.mid .midi .rmi     audio/mid
.bmp     image/bmp
.gif     image/gif
.png    image/png
.tif .tiff    image/tiff
.jpe .jpeg .jpg     image/jpeg
.txt      text/plain
.xml     text/xml
.html     text/html
.css      text/css
.js        text/javascript
.mht .mhtml   message/rfc822


展示文件

想着图片之类的还展示图片  其他类型的使用文件名字 + 链接跳转过去 下载或其他

先用php获取文件地址   全部放到数组里   然后对数组遍历输出即可。

 获取文件地址

$prin = traverseDir('./upload');$num = count($prin);/*** 遍历指定路径的文件夹中的文件* @param $dirPath 文件绝对路径* @param $type 遍历方法 默认参数为 $type='all' 返回所有文件作为一维数组返回,如果$type='file',则与多维数组返回* @return array 检索到文件成功返回内部文件路径数组,失败返回false;*/
function traverseDir($dirPath=false,$type='all'){//检测是否为文件夹if(!$dirPath||!is_dir($dirPath)){return false;}$files = array();//增加一个@抑制错误if(@$handle = opendir($dirPath)){while(($file=readdir($handle))!==false){//排除'.'当前目录和'..'上级目录if($file != '..' && $file != '.'){//只记录文件if($type == 'file'){if(is_dir($dirPath.DIRECTORY_SEPARATOR.$file)){//如果是文件夹,则重新遍历该文件的文件$files[$file] = traverseDir($dirPath.DIRECTORY_SEPARATOR.$file,'file');//把文件存入数组中foreach($files[$file] as $k => $v){if(is_file($v)){$files[] = $v;//删除源数组中的对应文件路径unset($files[$file][$k]);}}//删除源数组中的对应文件路径数组unset($files[$file]);}else{//如果是文件则直接存入数组$files[] = $dirPath.DIRECTORY_SEPARATOR.$file;}}else{//记录含文件if(is_dir($dirPath.DIRECTORY_SEPARATOR.$file)){//如果是文件夹,则重新遍历该文件的文件$files[$file] = traverseDir($dirPath.DIRECTORY_SEPARATOR.$file);}else{//如果是文件则直接存入数组$files[] = $dirPath.DIRECTORY_SEPARATOR.$file;}}}}closedir($handle);}return $files;
}

 开始展示文件

    for($i=0;$i<$num;++$i){if($i%5==0){echo '</ul><ul>';}$name = substr($prin[$i],9);if(strpos($name,'.png')!== false || strpos($name,'.jpg')!== false){echo  '<li><img src=" '.$prin[$i].' "></li>';}else{echo  '<li><a href="'.$prin[$i].'">'.$name.'</a></li>';}}

美化或优化


  1.  由于php发送表单时,会跳转到别的页面    两种方法解决

    一 使用ajax传输数据   可惜我不会

    二 跳转过去后   再使用js跳转过来 

  2. input的美化   

    可以使input标签隐藏  然后用另外的标签来代替input

    利用javascrip实现



完整代码

<?php
// print_r(traverseDir('./upload'));
$prin = traverseDir('./upload');$num = count($prin);/*** 遍历指定路径的文件夹中的文件* @param $dirPath 文件绝对路径* @param $type 遍历方法 默认参数为 $type='all' 返回所有文件作为一维数组返回,如果$type='file',则与多维数组返回* @return array 检索到文件成功返回内部文件路径数组,失败返回false;*/
function traverseDir($dirPath=false,$type='all'){//检测是否为文件夹if(!$dirPath||!is_dir($dirPath)){return false;}$files = array();//增加一个@抑制错误if(@$handle = opendir($dirPath)){while(($file=readdir($handle))!==false){//排除'.'当前目录和'..'上级目录if($file != '..' && $file != '.'){//只记录文件if($type == 'file'){if(is_dir($dirPath.DIRECTORY_SEPARATOR.$file)){//如果是文件夹,则重新遍历该文件的文件$files[$file] = traverseDir($dirPath.DIRECTORY_SEPARATOR.$file,'file');//把文件存入数组中foreach($files[$file] as $k => $v){if(is_file($v)){$files[] = $v;//删除源数组中的对应文件路径unset($files[$file][$k]);}}//删除源数组中的对应文件路径数组unset($files[$file]);}else{//如果是文件则直接存入数组$files[] = $dirPath.DIRECTORY_SEPARATOR.$file;}}else{//记录含文件if(is_dir($dirPath.DIRECTORY_SEPARATOR.$file)){//如果是文件夹,则重新遍历该文件的文件$files[$file] = traverseDir($dirPath.DIRECTORY_SEPARATOR.$file);}else{//如果是文件则直接存入数组$files[] = $dirPath.DIRECTORY_SEPARATOR.$file;}}}}closedir($handle);}return $files;
}echo '
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>beink</title><link rel="shortcut icon " type="images/x-icon" href="https://beink.cn/4.png"><style>*{margin: 0;padding: 0;}html,body{perspective: 800px;}body{background-color: rgba(255, 255, 255, 0.582);}.all{position: relative;width: 1000px;height: 800px;background-color: gray;box-shadow: 0 0 10px ;border-radius: 20px;margin: 50px auto;}li{list-style: none;}form{height: 200px;text-align: center;}input[type="submit"] {border: none;width: 120px;height: 50px;background-color: #00a1d6;border-radius: 10px;transition: .3s;color: white;}input[type="submit"]:hover{box-shadow: 0 0 10px #03befc;font-size: 20px;letter-spacing: 3px;}input[type="file"]{font-size: 25px;background-color: rgb(98, 98, 230);border-radius: 10px;transition: .3s;}input[type="file"]:hover{background-color: rgb(131, 131, 255);letter-spacing:1px;color: rgba(56, 54, 54, 0.575);}lable{font-size: 20px;}ul{position: relative;display: flex;flex-direction: row;justify-content: space-around;align-items: center;}li{margin-top:50px;}a{width: 190px;height: 80px;text-align: center;line-height:80px;display: block;text-decoration: none;color: orange;transition: .3s;border-radius: 10px;overflow:hidden;}a:hover{font-size: 20px ;background-color: rgb(107, 93, 93);}.fre{background-color: rgb(114, 106, 106);width: 100%;height: 600px;border-radius: 20px;}img{height:100px;transition:.3s;filter:blur(0.5px);}img:hover{transform:scale(1.5);filter:blur(0px);}</style>
</head>
<body><div class="all"><form action="form.php" method="post" onsubmit="return checkinput();" enctype="multipart/form-data"><br><br><br><input type="file" name="file" id="file"><br><br><br><input type="submit" class="submit"  onclick="validate()" name="submit" value="上  传"></form><script>var a = true;function validate(){var file = document.getElementById("file").value;if(file==""){const int = document.querySelector(".submit");int.style.backgroundColor="red";int.style.fontSize = "25px";int.value = "失  败"function move(){int.style.backgroundColor="#00a1d6";int.value = "上  传"int.style.fontSize = "16px";}setTimeout(move,2000);a=false;return;}else{a=true;}}function checkinput(){return a;}</script><div class="fre">';for($i=0;$i<$num;++$i){if($i%5==0){echo '</ul><ul>';}$name = substr($prin[$i],9);if(strpos($name,'.png')!== false || strpos($name,'.jpg')!== false){echo  '<li><img src=" '.$prin[$i].' "></li>';}else{echo  '<li><a href="'.$prin[$i].'">'.$name.'</a></li>';}}echo '</div></div>
</body>
</html>
';if($_SERVER["REQUEST_METHOD"] == "POST" && empty($_POST["file"]) !== false){$allowedExts = array("gif", "jpeg", "jpg", "png","zip","rar","tar",'tgz',"txt","xml","html","css","js");$temp = explode(".", $_FILES["file"]["name"]);// echo $_FILES["file"]["size"];$extension = end($temp);     // 获取文件后缀名if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/jpg")|| ($_FILES["file"]["type"] == "image/pjpeg")|| ($_FILES["file"]["type"] == "image/x-png")|| ($_FILES["file"]["type"] == "image/png")|| ($_FILES["file"]["type"] == "application/octet-stream")|| ($_FILES["file"]["type"] == "application/x-tar")|| ($_FILES["file"]["type"] == "application/x-compressed")|| ($_FILES["file"]["type"] == "application/x-zip-compressed")|| ($_FILES["file"]["type"] == "text/plain")|| ($_FILES["file"]["type"] == "text/xml")|| ($_FILES["file"]["type"] == "text/html")|| ($_FILES["file"]["type"] == "text/css")|| ($_FILES["file"]["type"] == "text/javascript"))&& ($_FILES["file"]["size"] < 20480000)   && in_array($extension, $allowedExts)){if ($_FILES["file"]["error"] > 0){echo "错误:: " . $_FILES["file"]["error"] . "<br>";}else{echo '<script>const int = document.querySelector(".submit");int.style.backgroundColor="gold";int.style.fontSize = "25px";int.value = "成  功"function move(){location = "原来的网址";}setTimeout(move,2000);</script>';move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);}}else{echo '<script>const int = document.querySelector(".submit");int.style.backgroundColor="red";int.style.fontSize = "25px";int.value = "失  败"function move(){location = "原来的网址";}setTimeout(move,1000);</script>';}}?>

这篇关于PHP 实现网页文件上传 及 文件展示的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/179216

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函