buhao 发表于 2015-8-27 11:54:29

Ajax & PHP 边学边练 之五 图片处理

  在上一篇中讲解了如何通过Ajax提交表单并由PHP处理底层数据,本篇将主要介绍图片的上传与处理。对于文件的上传很简单,只需一个Form便可实现,再通过PHP将源文件上传到目标目录。先上个效果图:

  Sample6_1.php 中创建Form:
//显示上传状态和图片
<div id=&quot;showimg&quot;></div>
//上传文件需要定义enctype,为了显示图片将target设为uploadframe
<form id=&quot;uploadform&quot; action=&quot;process_upload.php&quot; method=&quot;post&quot;
enctype=&quot;multipart/form-data&quot; target=&quot;uploadframe&quot;>
Upload a File:<br />
<input type=&quot;file&quot; id=&quot;myfile&quot; name=&quot;myfile&quot; />
//上传文件
<input type=&quot;submit&quot; value=&quot;Submit&quot;
onclick=&quot;uploadimg(document.getElementById('uploadform')); return false;&quot; />
<iframe id=&quot;uploadframe&quot; name=&quot;uploadframe&quot;
src=&quot;process_upload.php&quot; class=&quot;noshow&quot;></iframe>
</form>
  
  上传图片函数 uploadimg:

function uploadimg(theform){
//提交Form
theform.submit();
//在showimg <div>中显示上传状态
setStatus (&quot;Loading...&quot;,&quot;showimg&quot;);
}
//上传状态函数
function setStatus (theStatus, theObj){
obj = document.getElementById(theObj);
if (obj){
obj.innerHTML = &quot;<div class=\&quot;bold\&quot;>&quot; + theStatus + &quot;</div>&quot;;
}
}
  
  process_upload.php 提供文件上传功能:

<?php
//提供图片类型校验
$allowedtypes = array(&quot;image/jpeg&quot;,&quot;image/pjpeg&quot;,&quot;image/png&quot;,
                      &quot;image/x-png&quot;,&quot;image/gif&quot;);
//文件存放目录
$savefolder = &quot;images&quot;;
//如果有文件上传就开始干活
if (isset ($_FILES['myfile'])){
//检查上传文件是否符合$allowedtypes类型
if (in_array($_FILES['myfile']['type'],$allowedtypes)){
if ($_FILES['myfile']['error'] == 0){
$thefile = &quot;$savefolder/&quot;.$_FILES['myfile']['name'];
//通过move_uploaded_file上传文件
if (!move_uploaded_file($_FILES['myfile']['tmp_name'], $thefile)){
echo &quot;There was an error uploading the file.&quot;;
}
else{
?>
<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;>
<html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;>
<head>
<script type=&quot;text/javascript&quot; src=&quot;functions.js&quot;></script>
</head>
<body>
<!-- 显示图片 -->
<img src=&quot;<?php echo $thefile; ?>&quot;
       onload=&quot;doneloading(parent,'<?php echo $thefile; ?>')&quot; />
</body>
</html>
<?php
}
}
}
}
?>
  
  上面代码最后部分的doneloading 函数就是用来显示图片及修改图片尺寸大小。其中会用到thumb.php,它会在images目录中生成出源图片的大、中、小三个尺寸,有兴趣可以研究一下。欢迎大家拍砖~
  
  源代码下载
页: [1]
查看完整版本: Ajax & PHP 边学边练 之五 图片处理