php ajaxfileupload实现ajax文件上传功能

最近公司要做一个上传头像的功能,我们希望用户点击上传就实现了文件上传并不需要跳转页面了,下面我们就一起来看个例子吧.

可以批量进行添加上传,简单方便,代码如下:

  1. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  2. <script
  3. type="text/javascript" src="ajaxfileupload.js"></script>
  4. <form action="" method="post" enctype="multipart/form-data">
  5. <input size='80' /><br> <input type="file" name="file1"
  6. size="30" /> <input type="button" value="上传"
  7. onclick="return ajaxFileUpload();" /> <span
  8. >UpLoading...</span>
  9. </form>
  10. <script type="text/javascript">
  11. var str = '';
  12. function ajaxFileUpload(){
  13. $("#msg")
  14. .ajaxStart(function(){
  15. $(this).show();
  16. });
  17. /*
  18. .ajaxComplete(function(){
  19. $(this).hide();
  20. });
  21. */
  22. $.ajaxFileUpload(
  23. {
  24. url:'up_deal.php',
  25. secureuri:false,
  26. fileElementId:'file1',
  27. dataType: 'text',
  28. //data:{name:'qinmi', id:'123'},
  29. success: function(data){
  30. if(data=='error'){
  31. $('#msg').html("<span >上传失败</span>");
  32. }else{
  33. $('#msg').html("<span >上传成功</span>");
  34. str += data+'@';
  35. $('#fname').val(str);
  36. }
  37. }
  38. }
  39. );
  40. return false;
  41. }
  42. </script>

up_deal.php代码如下:

  1. <?php
  2. if ((($_FILES["file1"]["type"] == "image/gif")
  3. || ($_FILES["file1"]["type"] == "image/jpeg")
  4. || ($_FILES["file1"]["type"] == "image/bmp")
  5. || ($_FILES["file1"]["type"] == "image/pjpeg"))
  6. && ($_FILES["file1"]["size"] < 100000)){//100KB
  7. $extend = explode(".",$_FILES["file1"]["name"]);
  8. $key = count($extend)-1;
  9. $ext = ".".$extend[$key];
  10. $newfile = time().$ext;
  11. if(!file_exists('upload')){mkdir('upload');}
  12. move_uploaded_file($_FILES["file1"]["tmp_name"],"upload/" . $newfile);
  13. @unlink($_FILES['file1']);
  14. echo $newfile;
  15. }else {
  16. echo 'error';
  17. }
  18. ?>
其中需要用到ajaxfileupload.js 这个文件.