php 异步上传图片几种方法总结

要实现异步上传图片方法有常用的有二种,一种是利用iframe实现,另一种是借助于ajax来实现一般用第三方插件了,上传图片form提交target到一个隐藏的iframe里,代码如下 :

  1. form action="upload.php" name="form1" enctype="multipart/form-data" method="post" target="uploadIframe">
  2. <!--上传图片页面 -->
  3. </form>
  4. <iframe name="uploadIframe" ></iframe>

然后后台处理完上传图片逻辑后返回给前台,利用ajax修改当前页面DOM对象实现无刷新上传图片的友好功能,实例代码如下:a.html

  1. <form enctype="multipart/form-data" action="a.php" target="ifram_sign" method="POST">
  2. <input name="submit" value="" type="hidden">
  3. <label>上传文件: <input name="test_file" type="file" size="48"></label>
  4. <input type="image" value="立即上传" >
  5. </form>
  6. <iframe name="ifram_sign" src="" frame height="0" width="0" marginheight="0" marginwidth="0"></iframe>

PHP代码如下:

  1. <?php
  2. if ($_FILES["test_file"]["error"] > 0)
  3. {
  4. echo "Error: " . $_FILES["test_file"]["error"] . "<br />";
  5. }//开源代码phpfensi.com
  6. else
  7. {
  8. //这里的判断图片属性的方法就不写了。自己扩展一下。
  9. $filetype=strrchr($_FILES["test_file"]["name"],".");
  10. $filetype=substr($filetype,1,strlen($filetype));
  11. $filename="img/".time("YmdHis").".".$filetype;
  12. move_uploaded_file($_FILES["test_file"]["tmp_name"],$filename);
  13. echo '<script >alert(1)</script>';
  14. $return="parent.document.getElementByIdx_x('mpic".$pageset_id."').innerHTML='".$dataimgpath."'";
  15. echo "<script >alert('上传成功')</script>";
  16. echo "<script>{$return}</script>";
  17. }
  18. ?>

其实jquery ajax图片异步上传,HTML:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:>
  4. <head>
  5. <title>图片异步上传</title>
  6. </head>
  7. <script type="text/javascript" src="js/jquery.js"></script>
  8. <script type="text/javascript" src="js/index.js"></script>
  9. <link type="text/css" rel="stylesheet" href="css/index.css">
  10. <body>
  11. <div class="frm">
  12. <form name="uploadFrom" action="upload.php" method="post" target="tarframe" enctype="multipart/form-data">
  13. <input type="file" name="upfile">
  14. </form>
  15. <iframe src="" width="0" height="0" name="tarframe"></iframe>
  16. </div>
  17. <div >
  18. </div>
  19. </body>
  20. </html>

index.js,代码如下:

  1. $(function(){
  2. $("#upload_file").change(function(){
  3. $("#uploadFrom").submit();
  4. });
  5. });
  6. function stopSend(str){
  7. var im="<img src='upload/images/"+str+"'>";
  8. $("#msg").append(im);
  9. }

upload.php

  1. <?php
  2. $file=$_FILES['upfile'];
  3. $name=rand(0,500000).dechex(rand(0,10000)).".jpg";
  4. move_uploaded_file($file['tmp_name'],"upload/images/".$name);
  5. //调用iframe父窗口的js 函数
  6. echo "<script>parent.stopSend('$name')</script>";
  7. ?>