前端代码:
<form action="upload.php" enctype="multipart/form-data" method="post">
上传文件<input type="file" name="myfile"/>
<input type="submit" value="上传"/>
</form>
后端代码:
$upload_path = dirname(__FILE__).'/upload/';
//var_dump($_FILES);exit;
if(!is_dir($upload_path)) {
mkdir($upload_path);
}
$file_type = get_ext($_FILES['myfile']['name']);
echo $file_type;
if($file_type!="xls" && $file_type!='xlsx') {
echo "只支持excel导入";
exit();
}
//判断是否上传成功(是否使用post方式上传)
if(is_uploaded_file($_FILES['myfile']['tmp_name'])) {
//把文件转存到你希望的目录(不要使用copy函数)
$uploaded_file=$_FILES['myfile']['tmp_name'];
//$move_to_file=$user_path."/".$_FILES['myfile']['name'];
$file_true_name=$_FILES['myfile']['name'];
$move_to_file = $upload_path."/".time().rand(1,1000).$file_type;
//echo "$uploaded_file $move_to_file";
if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {
echo $_FILES['myfile']['name']."上传成功";
} else {
echo "上传失败";
}
} else {
echo "上传失败";
}
function get_ext($file_name){
$build_file_arr = explode('.', $file_name);
return array_pop($build_file_arr);
}