在中讲解了如何通过Ajax提交表单并由PHP处理底层数据,本篇将主要介绍图片的上传与处理。对于文件的上传很简单,只需一个Form便可实现,再通过PHP将源文件上传到目标目录。先上个效果图: Sample6_1.php 中创建Form: //显示上传状态和图片 div id= showimg
在中讲解了如何通过Ajax提交表单并由PHP处理底层数据,本篇将主要介绍图片的上传与处理。对于文件的上传很简单,只需一个Form便可实现,再通过PHP将源文件上传到目标目录。先上个效果图:
Sample6_1.php 中创建Form:
<span>//显示上传状态和图片</span> <div id="<span>showimg</span>"></div> <span>//上传文件需要定义enctype,为了显示图片将target设为uploadframe</span>
上传图片函数 uploadimg:
<span>function</span> uploadimg(theform){ <span>//提交Form</span> theform.submit(); <span>//在showimg <div>中显示上传状态 setStatus ("<span>Loading...</span>","<span>showimg</span>"); } <span>//上传状态函数</span> <span>function</span> setStatus (theStatus, theObj){ obj = <span>document</span>.getElementById(theObj); <span>if</span> (obj){ obj.innerHTML = "<span><div class='\"bold\"'>" + theStatus + "<span></span> </div></span>"; } } <p> </p> <p>process_upload.php 提供文件上传功能:</p> <pre class="brush:php;toolbar:false"><span></span>php <span>//提供图片类型校验</span> $allowedtypes = array("<span>image/jpeg</span>","<span>image/pjpeg</span>","<span>image/png</span>",<br> "<span>image/x-png</span>","<span>image/gif</span>"); <span>//文件存放目录</span> $savefolder = "<span>images</span>"; <span>//如果有文件上传就开始干活</span> if (isset ($_FILES['<span>myfile</span>'])){ <span>//检查上传文件是否符合$allowedtypes类型</span> if (in_array($_FILES['<span>myfile</span>']['<span>type</span>'],$allowedtypes)){ if ($_FILES['<span>myfile</span>']['<span>error</span>'] == 0){ $thefile = "<span>$savefolder/</span>".$_FILES['<span>myfile</span>']['<span>name</span>']; <span>//通过move_uploaded_file上传文件</span> if (!move_uploaded_file($_FILES['<span>myfile</span>']['<span>tmp_name</span>'], $thefile)){ echo "<span>There was an error uploading the file.</span>"; } else{ <span>?></span> <span>!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"<span>></span> <span><span>html</span> <span>xmlns</span>=<span>"http://www.w3.org/1999/xhtml"</span><span>></span> <span><span>head</span><span>></span> <span><span>script</span> <span>type</span>=<span>"text/javascript"</span> <span>src</span>=<span>"functions.js"</span><span>></span><span></span><span>script</span><span>></span> <span></span><span>head</span><span>></span> <span><span>body</span><span>></span> <span><!-- 显示图片 --></span> <span><span>img</span> <span>src</span>=<span>"<?php echo $thefile; ?>"</span> <br> <span>onload</span>=<span>"doneloading(parent,'<?php echo $thefile; ?>')"</span> <span>/></span> <span></span><span>body</span><span>></span> <span></span><span>html</span><span>></span> <span></span>php } } } } <span>?></span></span></span></span></span></span></span>
上面代码最后部分的doneloading 函数就是用来显示图片及修改图片尺寸大小。其中会用到thumb.php,它会在images目录中生成出源图片的大、中、小三个尺寸,有兴趣可以研究一下。欢迎大家拍砖~
源代码下载