在中讲解了如何通过ajax提交表单并由php处理底层数据,本篇将主要介绍图片的上传与处理。对于文件的上传很简单,只需一个form便可实现,再通过php将源文件上传到目标目录。先上个效果图: sample6_1.php 中创建form: //显示上传状态和图片 div id= showimg
在中讲解了如何通过ajax提交表单并由php处理底层数据,本篇将主要介绍图片的上传与处理。对于文件的上传很简单,只需一个form便可实现,再通过php将源文件上传到目标目录。先上个效果图:
sample6_1.php 中创建form:
//显示上传状态和图片
//上传文件需要定义enctype,为了显示图片将target设为uploadframe
upload a file:
name=myfile /> //上传文件 onclick=uploadimg(document.getelementbyid('uploadform')); return false; /> name=uploadframe
src=process_upload.php class=noshow>
上传图片函数 uploadimg:
function uploadimg(theform){ //提交form theform.submit(); //在showimg 中显示上传状态 setstatus (loading...,showimg);}//上传状态函数function setstatus (thestatus, theobj){ obj = document.getelementbyid(theobj); if (obj){ obj.innerhtml = + thestatus +
; }}
process_upload.php 提供文件上传功能:
php//提供图片类型校验$allowedtypes = array(image/jpeg,image/pjpeg,image/png,
image/x-png,image/gif);//文件存放目录$savefolder = images;//如果有文件上传就开始干活if (isset ($_files['myfile'])){ //检查上传文件是否符合$allowedtypes类型 if (in_array($_files['myfile']['type'],$allowedtypes)){ if ($_files['myfile']['error'] == 0){ $thefile = $savefolder/.$_files['myfile']['name']; //通过move_uploaded_file上传文件 if (!move_uploaded_file($_files['myfile']['tmp_name'], $thefile)){ echo there was an error uploading the file.; } else{?>!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>script type=text/javascript src=functions.js>script>head>body> img src=
onload=doneloading(parent,'') />body>html>php } } }}?>
上面代码最后部分的doneloading 函数就是用来显示图片及修改图片尺寸大小。其中会用到thumb.php,它会在images目录中生成出源图片的大、中、小三个尺寸,有兴趣可以研究一下。欢迎大家拍砖~
源代码下载