前一阶段工作中有一个需求为:上传excel文件并将excel内的数据导入数据库。
根据需要参考了一些代码写了个excel文件上传后导入完毕删除文件的代码文件
(为什么上传完毕要删除呢?我考虑到如果上传文件较多,会浪费服务器的储存空间,
且这些excel文件上传,导入后基本上没什么用处了,因此决定将其删除。)
根据菜鸟教程上的上传实例,改造了一下,代码如下:
$allowedExts = array("xls"); //限制上传文件类型
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp); // 获取文件后缀名
if (($_FILES["file"]["size"] < 2048000) && in_array($extension, $allowedExts)) //设置文件大小 及 判断是否为限制文件类型
{
if ($_FILES["file"]["error"] > 0)
{
message('文件上传失败,错误信息:' . $_FILES["file"]["error"],url('communityInfo/household'),'error');
}
//上传错误 返回错误信息
else
{
if (file_exists(IA_ROOT."/attachment/upload/" . $_FILES["file"]["name"]))
{
message('文件上传失败,错误信息:' . $_FILES["file"]["name"]. " 文件已经存在。",url('communityInfo/household'),'error');
} //判断文件是否存在
else
{
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
move_uploaded_file($_FILES["file"]["tmp_name"], IA_ROOT."/attachment/upload/" . $_FILES["file"]["name"]);
$filepath = IA_ROOT."/attachment/upload/" . $_FILES["file"]["name"];
// message('文件上传成功!',url('communityInfo/household'),'success');
// echo "文件存储在: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
message('文件上传失败,错误信息:文件格式非法!',url('communityInfo/household'),'error');
}
$whjImport = new whjImport("{$filepath}", 'structure');
$whjImport->Import();
//将excel中的数据导入数据库(封装为了一个类)
$filedel = IA_ROOT."/attachment/upload/";
delFile("{$filedel}");
//删除此文件
/*删除指定目录下的文件,不删除目录文件夹*/
function delFile($dirName){
if(file_exists($dirName) && $handle=opendir($dirName)){
while(false!==($item = readdir($handle))){
if($item!= "." && $item != ".."){
if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){
delFile($dirName.'/'.$item);
}else{
if(unlink($dirName.'/'.$item)){
return true;
}
}
}
}
closedir( $handle);
}
}
下面贴出菜鸟的上传实例(以上传图片为例)目录、代码:
目录:
说明:
upload 文件夹为上传文件储存的文件夹
form.html 前端
upload_file.php 后台代码
前端代码(form.html)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>图片上传</title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>
后台代码(upload_file.php)
<?php
header("Content-type: text/html; charset=utf-8");
//定义字符编码
$allowedExts = array("gif", "jpeg", "jpg", "png");
// 允许上传的图片后缀
$temp = explode(".", $_FILES["file"]["name"]);
echo "文件字节: ".$_FILES["file"]["size"] . "<br>";
//输出文件字节大小
$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"]["size"] < 204800) // 小于 200 kb
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "错误: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>";
// 判断当前目录下的 upload 目录是否存在该文件
// 如果没有 upload 目录,你需要创建它,upload 目录权限为 777
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " 文件已经存在。 ";
}
else
{
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
echo "文件原名:".$_FILES['file']['name']. "<br>";
$newPath = date("YmdHis").rand(100, 200).'.'.$temp[1];
//得到一个新的文件,即新的路径 用时间及一个随机字做文件名,防止上传的文件名称相同
$oldPath = $_FILES['file']['name'];
@rename($oldPath,$newPath);
//给文件重命名 @ 去除警告
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newPath);
echo "文件存储在: " . "upload/".$newPath;
}
}
}
else
{
echo "非法的文件格式";
}
?>
以上为很简单的图片上传程序。
上传文件类型,可以在form表单中做一个验证。
CSV 文件 (.csv)
<input type="file" accept=".csv" />
Excel 文件 2003-2007 (.xls类型)
<input type="file" accept="application/vnd.ms-excel" />
偷个懒,以下简写了
Excel文件 2010 (.xlsx类型)
accept=”application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”
.txt类型 —— accept=”text/plain”
.png/.jpg/etc (图片类型) ——accept=”image/*”
.htm,.html类型 ——accept=”text/html”
.avi, .mpg, .mpeg, .mp4(视频类型)—— accept=”video/*”
.mp3, .wav, etc(音频类型) —— accept=”audio/*”
.pdf类型 —— accept=”.pdf”
例子-DEMO:
http://jsfiddle.net/dirtyd77/LzLcZ/144/
其中要注意的是 accept="image/*"
或者其他几个“类型 + * ”
,页面的响应速度会很慢,用accept限制用户选择文件类型,但是,点击上传按钮的时候经常没反应,多点几下,过一段时间才会蹦出来。用户体验极差 ~
可以改成这样的形式:input type="file" accept="image/gif,image/jpeg,image/jpg,image/png
这样速度就很快了!
//以下是删除文件代码函数:
/*删除指定目录下的文件,不删除目录文件夹*/
function delFile($dirName){
if(file_exists($dirName) && $handle=opendir($dirName)){
//file_exists() 函数检查文件或目录是否存在 如果指定的文件或目录存在则返回 true,否则返回 false
//opendir() 函数打开目录句柄
while(false!==($item = readdir($handle))){
//readdir() 函数返回目录中下一个文件的文件名
if($item!= "." && $item != ".."){
if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){
//is_dir() 函数检查指定的文件是否是目录
delFile($dirName.'/'.$item);
}else{
if(unlink($dirName.'/'.$item)){
//unlink() 删除文件函数
return true;
}
}
}
}
closedir( $handle);
//closedir() 函数关闭目录句柄
}
}
delFile("./012");// 012为文件夹名称