您的位置:首页 > 编程语言 > PHP开发

PHP文件上传,下载,Sql工具类!

2017-04-19 21:46 369 查看

PHP文件上传,下载,Sql工具类! 对文件大小,文件类型 同名覆盖 中文转码的操作,可直接使用

前台 upload.html

<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form enctype="multipart/form-data" action="uploadProcess.php" method="post">
<table>
<tr><td align="center" colspan="2"><font style="font-size: 40px; font-family: 华文彩云;" >文件上传</font></td></tr>
<tr>
<td>请填写用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>介绍:</td>
<td><textarea name="intro" rows="10" cols="80"></textarea></td>
</tr>
<tr>
<td>请选择你要上传的文件</td>
<td><input type="file" name="myfile"></td>
</tr>
<tr><td><input type="submit" value="上传文件" /></td></tr>
</table>
</form>
</body>
</html>

 

 

控制器 FileProcess.php

<?php
require_once 'FileService.php';
$fileService = new FileService();

if (!empty($_REQUEST['flag'])) {
$flag = $_REQUEST['flag'];
//上传
if ($flag == "upload") {
$username = $_POST['username'];
$intro = $_POST['intro'];

$fileService -> Upload($username,$intro);
}elseif ($flag == "down") {
//接收要下载的文件名字
$filepath = $_GET['filepath'];
$filename = $_GET['filename'];

$fileService = new FileService();
$fileService->Download($filepath,$filename);

}
}

?>

 

后台 FileService.php

 

<?php
header("content_type:text/html;charset=utf-8");
require_once 'SqlHelper.php';
error_reporting(E_ALL & ~E_NOTICE);

class FileService{

//查询所有文件信息
function fileInfo(){

$sql = "select * from upload";
$sqlHelper = new SqlHelper();

$res = $sqlHelper->execute_dpl($sql);
return $res;

$res->free();
}

/*
*上传文件
*    功能
*        限制文件大小/类型
*        防止不同用户上传同名图片被覆盖的问题
*        防止同一用户上传的文件名相同的问题
*    参数
*        $username
*        $intro
*
*is_uploaded_file  上传到tmp缓存
*move_uploaded_file  移动到目标文件
*/
function Upload($username,$intro){

/*********对文件类型进行限制**********/

//获取文件的大小,限制上传文件的大小10M
$file_size = $_FILES['myfile']['size'];
if ($file_size>10*1024*1024) {
echo "<script>alert('上传失败,上传的文件不能超过10M的文件');history.go(-1);</script>";
//echo "上传失败,上传的文件不能超过10M的文件!";
exit();
}

//限制上传文件类型
/*
$file_type = $_FILES['myfile']['type'];
if ($file_type!='image/jpg' && $file_type!='image/pjpeg') {
echo "上传失败,文件类型只能是jpg格式!";
exit();
}*/

//判断文件是否上传成功
if (is_uploaded_file($_FILES['myfile']['tmp_name'])) {

/***防止不同用户上传同名图片被覆盖的问题->给每个用户创建一个文件夹*****/
//一般创建文件夹的时候根据id创建(username换成id,入参时带入id),防止汉字乱码
//给每个用户动态创建一个相应的文件夹
$user_path = $_SERVER['DOCUMENT_ROOT']."Demo/File/UpDown/upload/".$username;
//判断该用户是否已经有文件夹
if (!file_exists($user_path)) {
mkdir($user_path);
}

/****防止同一用户上传的文件名相同的问题->给每个文件名加上时间戳********/
//tmp里的文件名
$file_name = $_FILES['myfile']['name'];
//把缓存文件转存到你希望的目录
$uploaded_file = $_FILES['myfile']['tmp_name'];
//目标路径=(目标目录+用户名)+当前时间+后缀(strpos()字符串首次出现的位置)
$move_to_file = $user_path."/".time().rand(1,1000).substr($file_name, strpos($file_name, "."));

//对中文路径转码
$move_to_file = iconv("utf-8", "gb2312", $move_to_file);

/******************数据库操作***********************/
//存入数据库
$uptime = date('Y-m-d H:i:s');    //获取当前上传时间

$sql = "insert into upload (username,fname,fsize,uptime,fpath,intro) values ('$username','$file_name','$file_size','$uptime','$move_to_file','$intro')";

$sqlHelper = new SqlHelper();
$res = $sqlHelper->execute_dml($sql);

//判断是否将上传的文件移动到目标位置(先判断是否上传成功,再判断是否添加到数据库)
if (move_uploaded_file($uploaded_file, $move_to_file)) {

//res=1表示添加上传成功
if ($res == 1) {

echo "<script>alert('{$_FILES['myfile']['name']}文件上传成功');window.location.href='down.php';</script>";
}else{
echo "<script>alert('文件上传失败');history.go(-1);</script>";
}

}else{
echo "<script>alert('文件上传失败');history.go(-1);</script>";
}

}else{
echo "<script>alert('文件上传失败');history.go(-1);</script>";
}
}

/**
*
* 参数说明:
* 下载文件
*  $filepath     文件路径
*  $filename     文件名
*
*/
function Download($filepath,$filename){
//对中文文件名进行转码
$filename=iconv("UTF-8","GB2312",$filename);

if(!file_exists($filepath)){ //检查文件是否存在
echo "<script>alert('该文件不存在!');history.go(-1);</script>";
// echo "该文件不存在!";

return;
}

$fp = fopen($filepath, 'r');   //打开文件
$file_size = filesize($filepath);  //计算文件大小

if ($file_size>10*1024*1024) {

echo "<script>window.alert('文件过大,您没权限下载')</script>";
return;
}
//HTTP头部信息
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".$file_size);
header("Content-Disposition: attachment; filename=".$filename);

$buffer = 1024;
//为了下载安全,做一个文件字节读取计数器
$file_count = 0;
//判断文件是否结束 feof
while (!feof($fp) && ($file_size-$file_count > 0)) {

$file_data = fread($fp, $buffer);  //统计读了多少字节
$file_count+=$buffer;

echo "$file_data";  //把数据会送给浏览器
}
fclose($fp);
}

}

?>

 

 

 

 

工具类  SqlHelper.php

 

<?php

/**
*    sql工具类(dml,dpl,dpl_arr,close_link)
*
*1.创建MySqli对象
*2.操作数据库(发送sql)
*3.处理结果
*4.关闭资源
*
*/

class SqlHelper {
private $link;
private static $host = 'localhost';
private static $user = 'root';
private static $pwd = '';
private static $db = 'test';

public  function __construct() {

//初始化
$this->link = new MYSQLi(self::$host,self::$user,self::$pwd,self::$db);
if ($this->link->connect_error){
die("数据库连接失败".$this->link->connect_error);
}
$this->link->query("set names utf8");
}

/**
* dpl操作
* @param unknown $sql
*/
public function execute_dpl($sql){
$res = $this->link->query($sql) or die("操作dpl失败".$this->link->error);
return $res;
}

/**
* dpl操作
* @param $sql
* @return arr
*              把结果放在数组里。这样资源可以随时关闭,返回一个数组
*/

public function execute_dpl_arr($sql){
$arr = array();
$res = $this->link->query($sql) or die("操作dpl_arr失败".$this->link->error);
//把$res=>$arr,把结果集内容转移到一个数组中
while ($row = $res->fetch_assoc()){
$arr[] = $row;
}
//这里可以把资源立即关闭
$res->free();
return $arr;
}

/**
* dml操作  update/delete/insert
* @param unknown $sql
*/
public function execute_dml($sql){

$res = $this->link->query($sql) or die("操作dml失败".$this->link->error);
if (!$res){
return 0;   //失败
}else {
if ($this->link->affected_rows>0){
return 1;   //成功
}else {
return 2;   //没有行受到影响
}
}
$res->free();
}

//关闭链接
public function close_link(){
if (!empty($this->link)){
$this->link->close();
}
}

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: