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

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义