php+ajax文件上传

这是昨天在应用开发时用到的一款ajax图片上传功能了,方法很简单的就是把文件利用js给iframe来直接上传,如果上传文件成功返回1,再用js判断是否上传成功如果是就输出图片并显示预览效果,代码如下:

  1. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="content-type" content="text/html; charset=gb2312" />
  5. <title>ajax文件上传</title>
  6. <style type="text/css">
  7. #f1_upload_process { display:none;}
  8. </style>
  9. <script language="javascript" type="text/javascript">
  10. <!--
  11. function $(id)
  12. {
  13. return document.getelementbyid(id);
  14. }
  15. function startupload(){
  16. if( $('myfile').value =='' )
  17. {
  18. alert('请选择要上传图片!');
  19. return false;
  20. }
  21. var array = $('myfile').value.split('.');
  22. var ext = array[1].tolowercase();
  23. if( ext =="gif" || ext =="jpg" || ext =="png" )
  24. {
  25. $('f1_upload_process').style.display = 'block';
  26. $('f1_upload_form').style.display = 'block';
  27. return true;
  28. }
  29. else
  30. {
  31. alert('只允许上传gif jpg png格式图像文件!');
  32. return false;
  33. }
  34. }
  35. function stopupload(success,pic){
  36. var result = '';
  37. if (success ==1 ){
  38. result ='<img src='+pic+' />';
  39. $('logo').value=pic;
  40. }
  41. else {
  42. result = '<span class="emsg">logo图片上传失败,请联系开发人员!</span><br/><br/>';
  43. }
  44. $('f1_upload_process').style.display = 'none';
  45. $('f1_upload_form').innerhtml = result + '<br /><label><input name="myfile" type="file" size="30" /></label><label><input type="submit" name="submitbtn" class="sbtn" value="上传图片" /></label>';
  46. $('f1_upload_form').style.display = 'block';
  47. return true;
  48. }
  49. //-->
  50. </script>
  51. </head>
  52. <body>
  53. <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="javascript:return startupload();" >
  54. <span ><img src="loader.gif" /></span>
  55. <span align="center">
  56. <input name="myfile" type="file" size="30" />
  57. <input type="submit" name="submitbtn" class="sbtn" value="上传图片" />
  58. </span>
  59. <iframe name="upload_target" src="#" ></iframe>
  60. (可上传 gif,jpg,png)
  61. </form>
  62. </body>
  63. </html>

upload.php,代码如下:

  1. <?php
  2. $destination_path = '../../upfile/jianjulogo/';//getcwd().directory_separator;
  3. $result = 0;
  4. $target_path = $destination_path . basename( $_files['myfile']['name']);
  5. if(@move_uploaded_file($_files['myfile']['tmp_name'], $target_path)) {//开源代码phpfensi.com
  6. $result = 1;
  7. }
  8. echo $target_path;
  9. sleep(1);
  10. ?>
  11. <script language="javascript" type="text/javascript">window.top.window.stopupload(<?php echo $result; ?>,'<?=$target_path?>');</script>