php 上传文件并生成缩略图代码

 更新时间:2016年11月25日 16:29  点击:2473

if( isset($_FILES['upImg']) )
{
 if( $userGroup[$loginArr['group']]['upload'] == 0 )
 {
  echo '{"error":"您所在的用户组无权上传图片!"}';
 }
 else
 {
  $savePath = "attachment/img/".date('Y/m/d/H');

  mkDirs($savePath);

  $fileType = strtolower(strrchr($_FILES['upImg']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upImg']['size'] > 204800 )
  {
   echo '{"error":"图片不能超过200K!"}';
  }
  else
  {
   $saveImg = $savePath."/".$loginArr['uid']."_".time().rand().$fileType;

   if( @move_uploaded_file($_FILES['upImg']['tmp_name'], $saveImg) )
   {
    echo '{"error":"","msg":"http://'.$site_domain.$site_catalog.$saveImg.'"}';
   }
   else
   {
    echo '{"error":"图片上传失败!"}';
   }
  }
 }
}

if( $loginArr['state'] == 0 )
{
 echo '{"error":"您还没有登录!"}';
}
else
{
 $avatarPath = "attachment/avatar/".($loginArr['uid']%32)."/".($loginArr['uid']%257)."/".$loginArr['uid'];

 if( isset($_FILES['upAvatar']) )
 {
  mkDirs($avatarPath);

  $fileType = strtolower(strrchr($_FILES['upAvatar']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upAvatar']['size'] > 2097152 )
  {
   echo '{"error":"图片不能超过2MB!"}';
  }
  else
  {
   $imgInfo = @getimagesize($_FILES['upAvatar']['tmp_name']);

   if( !$imgInfo || !in_array($imgInfo[2], array(1,2,3)) )
   {
    echo '{"error":"系统无法识别您上传的文件!"}';
   }
   else
   {
    $TmpAvatar = $avatarPath."/temp".$fileType;
    
    if( @move_uploaded_file($_FILES['upAvatar']['tmp_name'], $TmpAvatar) )
    {
     $maxWidth = 520;

     $maxHeight = 520;

     if( $maxWidth > $imgInfo[0] || $maxHeight > $imgInfo[1] )
     {
      $maxWidth = $imgInfo[0];

      $maxHeight = $imgInfo[1];
     }
     else
     {
      if ( $imgInfo[0] < $imgInfo[1] )
       $maxWidth = ($maxHeight / $imgInfo[1]) * $imgInfo[0];
      else
       $maxHeight = ($maxWidth / $imgInfo[0]) * $imgInfo[1];
     }

     if( $maxWidth < 40 )
     {
      $maxWidth = 40;
     }

     if( $maxHeight < 40 )
     {
      $maxHeight = 40;
     }

     $image_p = imagecreatetruecolor($maxWidth, $maxHeight);

     switch($imgInfo[2])
     {
      case 1:
       $image = imagecreatefromgif($TmpAvatar);
       break;
      case 2:
       $image = imagecreatefromjpeg($TmpAvatar);
       break;
      case 3:
       $image = imagecreatefrompng($TmpAvatar);
       break;
     }

     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $imgInfo[0], $imgInfo[1]);

     imagejpeg($image_p, $avatarPath."/temp.jpg",100);

     imagedestroy($image_p);

     imagedestroy($image);

     if( $fileType != ".jpg" && file_exists($TmpAvatar) )
     {
      unlink($TmpAvatar);
     }

     echo '{"error":"","url":"'.$avatarPath.'/temp.jpg?'.rand().'","width":"'.$maxWidth.'","height":"'.$maxHeight.'"}';
    }
    else
    {
     echo '{"error":"图片上传失败!"}';
    }
   }
  }
 }

 if( isset($_POST['x'],$_POST['y'],$_POST['w'],$_POST['h']) )
 {
  if( is_numeric($_POST['x']) && is_numeric($_POST['y']) && $_POST['w'] > 0 && $_POST['h'] > 0 )
  {
   $image_p = imagecreatetruecolor(40, 40);

   $image = imagecreatefromjpeg($avatarPath."/temp.jpg");

   imagecopyresampled($image_p, $image, 0, 0, $_POST['x'], $_POST['y'], 40, 40, $_POST['w'], $_POST['h']);

   imagejpeg($image_p, $avatarPath."/40_40.jpg",100);

   imagedestroy($image_p);

   imagedestroy($image);

   unlink($avatarPath."/temp.jpg");

   echo "1";
  }
 }

 if( isset($_POST['avatar']) && $_POST['avatar'] == "delete" )
 {
  if( file_exists($avatarPath."/temp.jpg") )
  {
   unlink($avatarPath."/temp.jpg");
  }
 }
}

ob_end_flush();

已测(表结构:id 表ID(唯一)title 各类标题flid 类别的ID (大类为1 中类为2 小类为3)pid 上类的ID(大类就跟大类,提交中类的时候这地方写大类的ID,提交小类的时候写中类的ID) )

<?php   $link=mysql_connect("localhost","root","root") or die("数据库服务器连接错误".mysql_error());   mysql_select_db("sanji",$link) or die("数据库访问错误".mysql_error());   mysql_query("set character set gb2312");     mysql_query("set names gb2312");?><html><head><title>下拉框连动</title></head><body><script language="JavaScript"><!--var subcat = new Array();<?$i=0;$sql="select * from sanji where flid=2";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>var subcat2 = new Array();<?$i=0;$sql="select * from sanji where flid=3";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat2[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>function changeselect1(locationid){document.form1.s2.length = 0;document.form1.s2.options[0] = new Option('==请选择==','');for (i=0; i<subcat.length; i++){if (subcat[i][0] == locationid){document.form1.s2.options[document.form1.s2.length] = new Option(subcat[i][1], subcat[i][2]);}}}function changeselect2(locationid){document.form1.s3.length = 0;document.form1.s3.options[0] = new Option('==请选择==','');for (i=0; i<subcat2.length; i++){if (subcat2[i][0] == locationid){document.form1.s3.options[document.form1.s3.length] = new Option(subcat2[i][1], subcat2[i][2]);}}}//--></script>三级联动:<BR><form name="form1"><select name="s1" onChange="changeselect1(this.value)"><option>==请选择==</option><?$sql="select * from sanji where flid=1";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "<option value=".$arr["id"].">".$arr["title"]."</option>n";}?></select><select name="s2" onChange="changeselect2(this.value)"><option>==请选择==</option></select><select name="s3" onChange="alert('选选择'+this.value)"><option>==请选择==</option></select></form><BR></body></html>

数据库叫"sanji"-- phpMyAdmin SQL Dump-- version 2.11.4-- http://www.phpmyadmin.net---- 主机: localhost-- 生成日期: 2009 年 11 月 03 日 15:12-- 服务器版本: 5.0.51-- PHP 版本: 5.2.5SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";---- 数据库: `sanji`---- ------------------------------------------------------------ 表的结构 `sanji`--CREATE TABLE IF NOT EXISTS `sanji` (  `id` int(10) NOT NULL auto_increment,  `title` varchar(30) collate utf8_unicode_ci NOT NULL,  `flid` int(10) NOT NULL,  `pid` int(10) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;---- 导出表中的数据 `sanji`--INSERT INTO `sanji` (`id`, `title`, `flid`, `pid`) VALUES(1, '我是1', 1, 1),(2, '我是2,归1管', 2, 1),(3, '我是3,归2管', 3, 2),(4, '我是4,也归2管', 3, 2);

error_reporting(0);
session_start();
header("Content-Type:text/html;charset=utf-8");
require("config.php");
$_SESSION["cookie_jar1"]=tempnam("temp","C2");
$url=DZ."ajax.php?inajax=1&action=checkseccode&seccodeverify=".$_GET["code"];
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_COOKIEFILE,$_SESSION["cookie_jar"]);
curl_setopt($ch,CURLOPT_COOKIEJAR,$_SESSION["cookie_jar1"]);
$html=curl_exec($ch);
preg_match("/(?<=encoding=").*?(?=")/",$html,$charset);
if($charset[0]!=="utf-8")
{
 $html=iconv($charset[0],"utf-8",$html);
}
curl_close($ch);
preg_match("/(?<=CDATA[).*?(?=])/",$html,$outs);
echo $outs[0];
?>

error_reporting(0);
session_start();
require("config.php");
if(!is_dir("temp"))
{
 mkdir("temp",0777);
}
$c=tempnam("temp","c");
$url=DZ."logging.php?action=login";
 $ch=curl_init();
 curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
 curl_setopt($ch,CURLOPT_COOKIEJAR,$c);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
 $html=curl_exec($ch);
 preg_match("/(?<=charset=).*?(?=")/",$html,$charset);
 if($charset[0]!=="utf-8")
 {
  $html=iconv($charset[0],"utf-8",$html);
 }
 curl_close($ch);
 preg_match("/(?<=formhash" value=").*?(?=")/",$html,$outs);
 $_SESSION["hash"]=$outs[0];
 

$c1=tempnam("temp","c1");
$re_url=DZ."ajax.php?action=updateseccode&secchecktype=&inajax=1&ajaxtarget=seccodeverify_menu";
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$re_url);
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_COOKIEFILE,$c);
curl_setopt($ch,CURLOPT_COOKIEJAR,$c1);
$html=curl_exec($ch);
curl_close($ch);
preg_match("/(?<=src=").*?(?=")/",$html,$outs);

$_SESSION["cookie_jar"]=tempnam("temp","C1_");
$url=DZ.$outs[0];
$ch=curl_init();
curl_setopt($ch,CURLOPT_REFERER,$re_url);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_COOKIEFILE,$c1);
curl_setopt($ch,CURLOPT_COOKIEJAR,$_SESSION["cookie_jar"]);
$html=curl_exec($ch);
curl_close($ch);
echo $html;

ExcelFileParser处理excel获得数据 可作批量导入到数据库

提交表单

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Excel数据获取演示</title>
<meta name="Keywords" content="TODO" />
<meta name="Description" content="TODO"/>
</head>
<body>
    <div>
      <div>Excel数据获取演示</div>
      <div>
        <form method="POST" action="/Index/parse" enctype="multipart/form-data">
            <input type="file" name="excel" value="" />
            <input type="submit" name="submit" value="提交" />
        </form>
      </div>
    </div>
</body>
</html>


提交处理
[php]
<?php
/**
* CopyRight (c) 2009,
* All rights reserved.
* 文件名:
* 摘  要:
*
* @author 星期八 ixqbar@hotmail.com
* @version
*/

class IndexAction extends Action
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 默认索引页
     */
    public function index()
    {
        $this->display();
    }
    /**
     * 提交处理
     */
    public function parse()
    {
       /**
        * $_FILES数组说明
        * array(n) {
        *   ["表单文件框名称"] => array(5) {
        *       ["name"]        => 提交文件名称
        *       ["type"]        => 提交文件类型 Excel为"application/vnd.ms-excel"
        *       ["tmp_name"]    => 临时文件名称
        *       ["error"]       => 错误(0成功1文件太大超过upload_max_filesize2文件太大超过MAX_FILE3上传不完整4没有上传文件)
        *       ["size"]        => 文件大小(单位:KB)
        *   }
        * }
        */
        $return=array(0,'');
        /**
         * 判断是否提交
         * is_uploaded_file(文件名称)用于确定指定的文件是否使用POST方法上传,防止非法提交,通常和move_upload_file一起使用保存上传文件到指定的路径
         */
        if(!isset($_FILES) || !is_uploaded_file($_FILES['excel']['tmp_name']))
        {
            $return=array(1,'提交不合法');
        }
        //处理
        if(0 == $return[0])
        {
            import('@.Util.ExcelParser');
            $excel=new ExcelParser($_FILES['excel']['tmp_name']);
            $return=$excel->main();
        }
        //输出处理
        print_r($return);
    }
}
?>
[/php]

处理类
[php]
<?php
/**
* CopyRight (c) 2009,
* All rights reserved.
* 文件名:excel数据获取
* 摘  要:
*
* @author 星期八 ixqbar@hotmail.com
* @version 0.1
*/
class ExcelParser
{
    private $_data=array(0,'');
    private $_excel_handle;
    private $_excel=array();
    /**
     * 构造函数
     * @param <string> $filename 上传文件临时文件名称
     */
    public function __construct($filename)
    {
        /**
         * 引入excelparser类
         * 普通方法为
         * requires 路径.'excelparser.php';
         * import为ThinkPHP自带导入类方法
         */
        import('@.Util.PHPExcelParser.excelparser','','.php');
        $this->_excel_handle=new ExcelFileParser();
        //错误获取
        $this->checkErrors($filename);
    }
    /**
     * 错误校验
     */
    private function checkErrors($filename)
    {
        /**
         * 方法一
         */
        $error_code=$this->_excel_handle->ParseFromFile($filename);
        /**
         * 方法二
         * $file_handle = fopen($this->_filename,'rb');
         * $content = fread($file_handle,filesize($this->_filename));
         * fclose($file_handle);
         * $error_code = $this->_excel->ParseFromString($content);
         * unset($content,$file_handle);
         */
        switch($error_code)
        {
            case 0:
                //无错误不处理
                break;
            case 1:
                $this->_data=array(1,'文件读取错误(Linux注意读写权限)');
                break;
            case 2:
                $this->_data=array(1,'文件太小');
                break;
            case 3:
                $this->_data=array(1,'读取Excel表头失败');
                break;
            case 4:
                $this->_data=array(1,'文件读取错误');
                break;
            case 5:
                $this->_data=array(1,'文件可能为空');
                break;
            case 6:
                $this->_data=array(1,'文件不完整');
                break;
            case 7:
                $this->_data=array(1,'读取数据错误');
                break;
            case 8:
                $this->_data=array(1,'版本错误');
                break;
        }
        unset($error_code);
    }
    /**
     * Excel信息获取
     */
    private function getExcelInfo()
    {
        if(1==$this->_data[0])return;
        /**
         * 获得sheet数量
         * 获得sheet单元对应的行和列
         */
        $this->_excel['sheet_number']=count($this->_excel_handle->worksheet['name']);
        for($i=0;$i<$this->_excel['sheet_number'];$i++)
        {
            /**
             * 行于列
             * 注意:从0开始计数
             */
            $row=$this->_excel_handle->worksheet['data'][$i]['max_row'];
            $col=$this->_excel_handle->worksheet['data'][$i]['max_col'];
            $this->_excel['row_number'][$i]=($row==NULL)?0:++$row;
            $this->_excel['col_number'][$i]=($col==NULL)?0:++$col;
            unset($row,$col);
        }
    }
    /**
     * 中文处理函数
     * @return <string>
     */
    private function uc2html($str)
    {
        $ret = '';
        for( $i=0; $i<strlen($str)/2; $i++ )
        {
            $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
            $ret .= '&#'.$charcode.';';
        }
        return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES');
    }
    /**
     * Excel数据获取
     */
    private function getExcelData()
    {
        if(1==$this->_data[0])return;

        //修改标记
        $this->_data[0]=1;
        //获取数据
        for($i=0;$i<$this->_excel['sheet_number'];$i++)
        {
            /**
             * 对行循环
             */
            for($j=0;$j<$this->_excel['row_number'][$i];$j++)
            {
                /**
                 * 对列循环
                 */
                for($k=0;$k<$this->_excel['col_number'][$i];$k++)
                {
                    /**
                     * array(4) {
                     *   ["type"]   => 类型 [0字符类型1整数2浮点数3日期]
                     *   ["font"]   => 字体
                     *   ["data"]   => 数据
                     *   ...
                     * }
                     */
                    $data=$this->_excel_handle->worksheet['data'][$i]['cell'][$j][$k];
                    switch($data['type'])
                    {
                        case 0:
                            //字符类型
                            if($this->_excel_handle->sst['unicode'][$data['data']])
                            {
                                //中文处理
                                $data['data'] = $this->uc2html($this->_excel_handle->sst['data'][$data['data']]);
                            }
                            else
                            {
                                $data['data'] = $this->_excel_handle->sst['data'][$data['data']];
                            }
                            break;
                        case 1:
                            //整数
                            //TODO
                            break;
                        case 2:
                            //浮点数
                            //TODO
                            break;
                        case 3:
                            //日期
                            //TODO
                            break;
                    }
                    $this->_data[1][$i][$j][$k]=$data['data'];
                    unset($data);
                }
            }
        }
    }
    /**
     * 主函数
     * @return <array> array(标识符,内容s)
     */
    public function main()
    {
        //Excel信息获取
        $this->getExcelInfo();
        //Excel数据获取
        $this->getExcelData();
        return $this->_data;
    }
}

?>

[!--infotagslink--]

相关文章

  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • PHP判断上传文件类型的解决办法

    分享给大家php判断上传文件类型的方法,大家一起学习学习。/** * 读取文件前几个字节 判断文件类型 * @return String */ function checkTitle($filename){ $file=fopen($filename, "rb"); $bin=fread($file, 2); /...2015-10-21
  • c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
  • Vue使用formData格式类型上传文件的示例

    这篇文章主要介绍了Vue使用formData格式类型上传文件的示例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
  • c# FTP上传文件实例代码(简易版)

    下面小编就为大家分享一篇c# FTP上传文件的实例代码,超简单哦~希望对大家有所帮助。一起跟随小编过来看看吧,...2020-06-25
  • PHP批量生成图片缩略图(1/5)

    这款批量生成缩略图代码可以生成指定大小的小图哦,并且支持文件批量上传。 这款教程会用到php文件 view.php config.php funs.php index.php 功能: -------...2016-11-25
  • C#实现为一张大尺寸图片创建缩略图的方法

    这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
  • php 上传文件并生成缩略图代码

    if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
  • yii实现使用CUploadedFile上传文件的方法

    这篇文章主要介绍了yii实现使用CUploadedFile上传文件的方法,结合具体的前端与后端处理代码实例分析了CUploadedFile类的使用方法,需要的朋友可以参考下...2015-12-31
  • 阿里云OSS 通过表单直接上传文件 Post Policy例子

    本文章为各位简单介绍阿里云OSS 通过表单直接上传文件 Post Policy例子,这个例子非常的简单只需要简单的像php一样就可以了,具体如下。 代码如下 复制代...2016-11-25
  • CentOS下编译安装nginx及配置缩略图插件的方法教程

    这篇文章主要给大家介绍了在CentOS系统下编译安装nginx及配置缩略图插件的方法教程,文中给出了详细的安装步骤,对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。...2017-07-06
  • PHP响应post请求上传文件的方法

    这篇文章主要介绍了PHP响应post请求上传文件的方法,涉及php针对post传输数据处理的相关技巧,需要的朋友可以参考下...2015-12-21
  • c#多图片上传并生成缩略图的实例代码

    今天写了一个上传多张图片并生成缩略图的小程序。当然因为是菜鸟,所以写的一般。但还是学到了不少东西。现在上代码。...2021-09-22
  • Nginx配合php实现生成实时缩略图功能

    这篇文章主要介绍了Nginx配合php实现生成实时缩略图功能,这在一些特殊场合可能会要用到,需要的朋友可以参考下...2016-01-27
  • js通过canvas生成图片缩略图

    对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了...2020-10-03
  • php 图片上传代码(具有生成缩略图与增加水印功能)

    这款图片上传源代码是一款可以上传图片并且还具有给上传的图片生成缩略图与增加水印功能哦,可以说是一款完美的图片上传类哦。 代码如下 复制代码 ...2016-11-25
  • asp.net fileupload控件上传文件与多文件上传

    这篇文章主要介绍了asp.net fileupload控件上传文件的方法,fileupload控件多文件上传,以及fileupload上传时实现文件验证的方法,需要的朋友可以参考下...2021-09-22
  • C# jpg缩略图函数代码

    生成jpg缩略图字节,本人的小软件中需要用到的功能,所以自己做了一个函数,和大家分享 为什么要生成字节而不是文件,这是为了方便后续处理啦^_^...2020-06-25
  • php支持生成缩略图文件上传代码

    <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1...2016-11-25
  • 解决ASP.NET Core Mvc文件上传限制问题实例

    本篇文章主要介绍了解决ASP.NET Core Mvc文件上传限制问题,具有一定的参考价值,有需要的可以了解一下。...2021-09-22