PHP+Ajax图片上传并且无刷新生成缩略图预览
XML/HTML Code
<div id="upload-wrapper"> <div align="center"> <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> <input name="ImageFile" id="imageInput" type="file" /> <input type="submit" id="submit-btn" value="Upload" /> <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/> </form> <div id="output"></div> </div> </div>
JavaScript Code
<script type="text/javascript"> $(document).ready(function() { var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforeSubmit, // pre-submit callback success: afterSuccess, // post-submit callback resetForm: true // reset the form after successful submit }; $('#MyUploadForm').submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); function afterSuccess() { $('#submit-btn').show(); //hide submit button $('#loading-img').hide(); //hide submit button } //function to check file size before uploading. function beforeSubmit(){ //check whether browser fully supports all File API if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$('#imageInput').val()) //check empty input filed { $("#output").html("Are you kidding me?"); return false } var fsize = $('#imageInput')[0].files[0].size; //get file size var ftype = $('#imageInput')[0].files[0].type; // get file type //allow only valid image file types switch(ftype) { case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': break; default: $("#output").html("<b>"+ftype+"</b> Unsupported file type!"); return false } //Allowed file size is less than 1 MB (1048576) if(fsize>1048576) { $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor."); return false } $('#submit-btn').hide(); //hide submit button $('#loading-img').show(); //hide submit button $("#output").html(""); } else { //Output error to older unsupported browsers that doesn't support HTML5 File API $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!"); return false; } } //function to format bites bit.ly/19yoIPO function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } </script>
processupload.php
PHP Code
<?php if(isset($_POST)) { ############ Edit settings ############## $ThumbSquareSize = 200; //Thumbnail will be 200x200 $BigImageMaxSize = 500; //Image Maximum height or width $ThumbPrefix = "thumb_"; //Normal thumb Prefix $DestinationDirectory = '../upload/'; //specify upload directory ends with / (slash) $Quality = 90; //jpeg quality ########################################## //check if this is an ajax request if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die(); } // check $_FILES['ImageFile'] not empty if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])) { die('Something wrong with uploaded file, something missing!'); // output error when above checks fail. } // Random number will be added after image name $RandomNumber = rand(0, 9999999999); $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name $ImageSize = $_FILES['ImageFile']['size']; // get original image size $TempSrc = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder $ImageType = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc. //Let's check allowed $ImageType, we use PHP SWITCH statement here switch(strtolower($ImageType)) { case 'image/png': //Create a new image from file $CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']); break; case 'image/gif': $CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']); break; case 'image/jpeg': case 'image/pjpeg': $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']); break; default: die('Unsupported File!'); //output error and exit } //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder. //Get first two values from image, width and height. //list assign svalues to $CurWidth,$CurHeight list($CurWidth,$CurHeight)=getimagesize($TempSrc); //Get file extension from Image name, this will be added after random name $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); //remove extension from filename $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); //Construct a new name with random number and extension. $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt; //set the Destination Image $thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory $DestRandImageName = $DestinationDirectory.$NewImageName; // Image with destination directory //Resize image to Specified Size by calling resizeImage function. if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) { //Create a square Thumbnail right after, this time we are using cropImage() function if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) { echo 'Error Creating thumbnail'; } /* We have succesfully resized and created thumbnail image We can now output image to user's browser or store information in the database */ echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">'; echo '<tr>'; echo '<td align="center"><img src="../upload/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail"></td>'; echo '</tr><tr>'; echo '<td align="center"><img src="../upload/'.$NewImageName.'" alt="Resized Image"></td>'; echo '</tr>'; echo '</table>'; /* // Insert info into database table! mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath) VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')"); */ }else{ die('Resize Error'); //output error } } // This function will proportionally resize image function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType) { //Check Image size is not 0 if($CurWidth <= 0 || $CurHeight <= 0) { return false; } //Construct a proportional size of new image $ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); $NewWidth = ceil($ImageScale*$CurWidth); $NewHeight = ceil($ImageScale*$CurHeight); $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight); // Resize Image if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)) { switch(strtolower($ImageType)) { case 'image/png': imagepng($NewCanves,$DestFolder); break; case 'image/gif': imagegif($NewCanves,$DestFolder); break; case 'image/jpeg': case 'image/pjpeg': imagejpeg($NewCanves,$DestFolder,$Quality); break; default: return false; } //Destroy image, frees memory if(is_resource($NewCanves)) {imagedestroy($NewCanves);} return true; } } //This function corps image to create exact square images, no matter what its original size! function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType) { //Check Image size is not 0 if($CurWidth <= 0 || $CurHeight <= 0) { return false; } //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9 if($CurWidth>$CurHeight) { $y_offset = 0; $x_offset = ($CurWidth - $CurHeight) / 2; $square_size = $CurWidth - ($x_offset * 2); }else{ $x_offset = 0; $y_offset = ($CurHeight - $CurWidth) / 2; $square_size = $CurHeight - ($y_offset * 2); } $NewCanves = imagecreatetruecolor($iSize, $iSize); if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)) { switch(strtolower($ImageType)) { case 'image/png': imagepng($NewCanves,$DestFolder); break; case 'image/gif': imagegif($NewCanves,$DestFolder); break; case 'image/jpeg': case 'image/pjpeg': imagejpeg($NewCanves,$DestFolder,$Quality); break; default: return false; } //Destroy image, frees memory if(is_resource($NewCanves)) {imagedestroy($NewCanves);} return true; } }
以上就是我们要介绍的ajax无刷新图片上传功能了,其实就是通过异步模式提交给php然后由php上传图片并且生成小图返回给指定的id的htm元素模块即可。
数据库部分:
CREATE TABLE `username_list` ( `id` int(11) NOT NULL auto_increment, `username` varchar(60) character set latin1 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
js代码
<script type="text/javascript"> $(document).ready(function() { $("#username").keyup(function (e) { //removes spaces from username $(this).val($(this).val().replace(/s/g, '')); var username = $(this).val(); if(username.length < 4){$("#user-result").html('');return;} if(username.length >= 4){ $("#user-result").html('<img src="imgs/ajax-loader.gif" />'); $.post('check_username.php', {'username':username}, function(data) { $("#user-result").html(data); }); } }); }); </script> XML/HTML Code <div id="registration-form"> <label for="username">输入帐号: <input name="username" type="text" id="username" maxlength="15"> <span id="user-result"></span> </label> <br>输入的字符大于等于4才会检测 </div>
check_username.php
<?php include_once("conn.php"); //check we have username post var if(isset($_POST["username"])) { //check if its ajax request, exit script if its not if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { die(); } //trim and lowercase username $username = strtolower(trim($_POST["username"])); //sanitize username $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH); //check username in db $results = mysql_query("SELECT id FROM username_list WHERE username='$username'"); //return total count $username_exist = mysql_num_rows($results); //total records //if value is more than 0, username is not available if($username_exist) { die('<img src="imgs/not-available.png" />'); }else{ die('<img src="imgs/available.png" />'); } //close db connection } ?>PHP递归算法就是函数调用函数了操作非常的简单了,我们下面来给各位介绍PHP递归算法及实际的一些关于递归的用法。
递归函数为自调用函数,在函数体内直接或间接自己调用自己,但需要设置自调用的条件,若满足条件,则调用函数本身,若不满足则终止本函数的自调用,然后把目前流程的主控权交回给上一层函数来执行,可能这样给大家讲解,还是很难明白,直接上例子
function test ($n){ echo $n.” “; if($n>0){ test($n-1); }else{ echo “<?>”; } echo $n.” ” } test(2)
这个例子最终的输出结果是2 1 0<?>0 1 2
我解释下 为何输出是这样的
第一步,执行test(2),echo 2,然后因为2>0,执行test(1), 后面还有没来得及执行的echo 2
第二步,执行test(1),echo 1,然后因为1>0,执行test(0),同样后面还有没来得及执行的 echo 1
第三步,执行test(0),echo 0,执行test(0),echo 0, 此时0>0的条件不满足,不在执行test()函数,而是echo “<?>”,并且执行后面的 echo 0
此时函数已经不再调用自己,开始将流程的主控权交回给上一层函数来执行,也就是开始执行刚刚所有test()函数没来得及输出的最后一个echo,0的一层是1也就是输出1 1的上一层是2 也就是输出2 2没有山一层 所以呢 输出的内容就是2 1 0<?>0 1 2
如何考虑用PHP递归算法来解决问题
例:求s=1+2+3+4+5+6+……+n本来这个问题我们过去常用循环累加的方法。而这里如要用递归的方法,必须考虑两点:
1) 能否把问题转化成递归形式的描述;
2) 是否有递归结束的边界条件。
显然递归的两个条件都有了:
1) s(n) =s(n-1)+n
2) s(1)=1
所以源程序为:
int progression(int n){ int res; if (n=1 )res=1 else res=progression(n-1)+n; return res; }
中序遍历二叉树
void inorder (BinTree T){ if (T){ inorder(T->lchild); printf(“%c”,T->data); inorder(T->rchild); } }
Mysql
首先我们准备一张数据表class,记录商品分类信息。表中有三个字段,id:分类编号,主键自增长;title:分类名称;pid:所属上级分类id。
class表结构:
CREATE TABLE IF NOT EXISTS `class` ( `id` mediumint(6) NOT NULL AUTO_INCREMENT, `title` varchar(30) NOT NULL, `pid` mediumint(6) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
插入数据后,如图:
根据不同的需求,我们提供两种不同格式的自定义函数,一种是返回字符串,一种是返回数组,两种函数都使用了递归方法。先看返回字符串格式的函数:
function get_str($id = 0) { global $str; $sql = "select id,title from class where pid= $id"; $result = mysql_query($sql);//查询pid的子类的分类 if($result && mysql_affected_rows()){//如果有子类 $str .= '<ul>'; while ($row = mysql_fetch_array($result)) { //循环记录集 $str .= "<li>" . $row['id'] . "--" . $row['title'] . "</li>"; //构建字符串 get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 } $str .= '</ul>'; } return $str; }
以上函数get_str()通过递归,不断查询下级分类,并最终返回字符串,大家可以根据项目需求修改其中的str,最终生成一个无限分级列表:
include_once('connect.php'); //连接数据库,connect.php文件自己写一个啊 echo get_str(0); //输出无限级分类
效果如:
接着我们来看返回数组格式的函数,一样要使用递归:
function get_array($id=0){ $sql = "select id,title from class where pid= $id"; $result = mysql_query($sql);//查询子类 $arr = array(); if($result && mysql_affected_rows()){//如果有子类 while($rows=mysql_fetch_assoc($result)){ //循环记录集 $rows['list'] = get_array($rows['id']); //调用函数,传入参数,继续查询下级 $arr[] = $rows; //组合数组 } return $arr; } }
函数get_array()返回了数组,这是我们期待的,所以笔者推荐使用get_array()得到数组,这样一来,我们可以对数组进行任意操作,比如我们可以将数组转换成json格式的数据传给前端页面,前端页面可以通过解析json数据灵活展示分类信息。比如树形结构的分类列表,下拉分类列表等。
include_once('connect.php'); //连接数据库 $list = get_array(0); //调用函数 print_r($list); //输出数组
如果要输出json格式的数据,则可使用:
echo json_encode($list);
本文章为各位介绍解决yii webservice 提示:Procedure 'getSent' not present 错误方法,有兴趣的和小编一起看看。
其实根据常用的webservice清除缓存方法,在client端加入这样一句话:
ini_set("soap.wsdl_cache_enabled", "0");
应该就可以了,但是处理了好久,在本地测试没问题,放到服务器上就不行,一直提示:Procedure 'getSent' not present
后来查看PHP的配置文件php.ini,找到这样一句话: soap.wsdl_cache_dir="/tmp"
然后进入对应目录,看到有这样子的文件:
wsdl-root-37c8f47f71a35a60f667be40ae619d0b
wsdl开头的文件,都是webservice的缓存文件,删掉这些文件,再试,一切正常了。
Unicode编码我们用到的不多因为Unicode编码在源码中都是字符了,但有时会用到Unicode编码了,下面我们一起来看一篇PHP Unicode编码相互转换的例子,希望例子能够对各位有帮助。<?php /** * $str 原始中文字符串 * $encoding 原始字符串的编码,默认utf-8 * $prefix 编码后的前缀,默认"&#" * $postfix 编码后的后缀,默认";" */ function unicode_encode($str, $encoding = 'utf-8', $prefix = '&#', $postfix = ';') { //将字符串拆分 $str = iconv("UTF-8", "gb2312", $str); $cind = 0; $arr_cont = array(); for ($i = 0; $i < strlen($str); $i++) { if (strlen(substr($str, $cind, 1)) > 0) { if (ord(substr($str, $cind, 1)) < 0xA1) { //如果为英文则取1个字节 array_push($arr_cont, substr($str, $cind, 1)); $cind++; } else { array_push($arr_cont, substr($str, $cind, 2)); $cind+=2; } } } foreach ($arr_cont as &$row) { $row = iconv("gb2312", "UTF-8", $row); } //转换Unicode码 foreach ($arr_cont as $key => $value) { $unicodestr.= $prefix . base_convert(bin2hex(iconv('utf-8', 'UCS-4', $value)), 16, 10) .$postfix; } return $unicodestr; } /** * $str Unicode编码后的字符串 * $decoding 原始字符串的编码,默认utf-8 * $prefix 编码字符串的前缀,默认"&#" * $postfix 编码字符串的后缀,默认";" */ function unicode_decode($unistr, $encoding = 'utf-8', $prefix = '&#', $postfix = ';') { $arruni = explode($prefix, $unistr); $unistr = ''; for ($i = 1, $len = count($arruni); $i < $len; $i++) { if (strlen($postfix) > 0) { $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix)); } $temp = intval($arruni[$i]); $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256); } return iconv('UCS-2', $encoding, $unistr); } $str = "PHP二次开发:www.php2.cc"; $unistr = unicode_encode($str); $unistr2 = unicode_decode($unistr); echo $unistr . '<br />'; echo $unistr2 . '<br />'; $unistr = unicode_encode($str,'GBK','\\u'); $unistr2 = unicode_decode($unistr,'GBK','\\u'); echo $unistr . '<br />'; echo $unistr2 . '<br />';
相关文章
- PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
- 本案例非通用,仅作笔记以备用 修改后的结果是 百度编辑器里上传的图片路径为/d/file/upload1...2014-07-03
- 这篇文章主要介绍了Java实现将图片上传到webapp路径下 路径获取方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-11-12
- 这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
- 这款批量生成缩略图代码可以生成指定大小的小图哦,并且支持文件批量上传。 这款教程会用到php文件 view.php config.php funs.php index.php 功能: -------...2016-11-25
- 这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
- upload.php复制代码 代码如下:<?phpif(isset($_FILES["myfile"])){$ret = array();$uploadDir = 'images'.DIRECTORY_SEPARATOR.date("Ymd").DIRECTORY_SEPARATOR;$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.$upl...2014-06-07
- if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
ASP.NET百度Ueditor编辑器实现上传图片添加水印效果
这篇文章主要给大家介绍了ASP.NET百度Ueditor编辑器1.4.3这个版本实现上传图片添加水印效果的相关资料,文中通过图文及示例代码介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。...2021-09-22- 这篇文章主要介绍了Yii框架实现图片上传的方法,结合实例形式较为详细的分析了Yii框架实现图片上传功能的具体步骤与相关操作技巧,需要的朋友可以参考下 本文实例...2017-07-06
- 这款文件上传实用代码,可以方便的上传你指定的文件或图片,同时也可以快速的限制上传图片文件类或大小。 /* * created on 2010-6-21 * * the class for image...2016-11-25
- 这篇文章主要给大家介绍了在CentOS系统下编译安装nginx及配置缩略图插件的方法教程,文中给出了详细的安装步骤,对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。...2017-07-06
- 今天写了一个上传多张图片并生成缩略图的小程序。当然因为是菜鸟,所以写的一般。但还是学到了不少东西。现在上代码。...2021-09-22
- 这篇文章主要介绍了Nginx配合php实现生成实时缩略图功能,这在一些特殊场合可能会要用到,需要的朋友可以参考下...2016-01-27
- 对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了...2020-10-03
- 多文件上传其实就包括了图片及各种文件了,下面介绍的是一款PHP多文件上传类,一共两个文件,upp.php 和 uploadFile.php,upp.php,这是前台所显示的表单文件了,默认的是四个...2016-11-25
- 这款图片上传源代码是一款可以上传图片并且还具有给上传的图片生成缩略图与增加水印功能哦,可以说是一款完美的图片上传类哦。 代码如下 复制代码 ...2016-11-25
- 生成jpg缩略图字节,本人的小软件中需要用到的功能,所以自己做了一个函数,和大家分享 为什么要生成字节而不是文件,这是为了方便后续处理啦^_^...2020-06-25
- 分享一个网友写的php图片上传类,支持加水印,生成略缩图功能哦,面是配置和可以获取的一些信息(每一个配置信息都有默认值,如无特殊需要,可以不配置): 代码如下 ...2016-11-25
- <!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