PHP+Ajax图片上传并且无刷新生成缩略图预览

图片上传我们介绍过的教程非常的多了,今天我整理的这篇ajax图片上传主要有一个上传之后自动生成小图的功能并且还返回预览效果,下面我们来看看这段代码.

XML/HTML Code

  1. <div > <div align="center"> <form action="processupload.php" method="post" enctype="multipart/form-data" > <input name="ImageFile" type="file" /> <input type="submit" value="Upload" /> <img src="images/ajax-loader.gif" alt="Please Wait"/> </form> <div ></div> </div>
  2. /div>

JavaScript Code

  1. <script type="text/<a href="/js_a/js.html" target="_blank">javascript</a>">
  2. $(document).ready(function() {
  3. var options = {
  4. target: '#output', // target element(s) to be updated with server response
  5. beforeSubmit: beforeSubmit, // pre-submit callback
  6. success: afterSuccess, // post-submit callback
  7. resetForm: true // reset the form after successful submit
  8. };
  9. $('#MyUploadForm').submit(function() {
  10. $(this).ajaxSubmit(options);
  11. // always return false to prevent standard browser submit and page navigation
  12. return false;
  13. });
  14. });
  15. function afterSuccess()
  16. {
  17. $('#submit-btn').show(); //hide submit button
  18. $('#loading-img').hide(); //hide submit button
  19. }
  20. //function to check file size before uploading.
  21. function beforeSubmit(){
  22. //check whether browser fully supports all File API
  23. if (window.File && window.FileReader && window.FileList && window.Blob)
  24. {
  25. if( !$('#imageInput').val()) //check empty input filed
  26. {
  27. $("#output").html("Are you kidding me?");
  28. return false
  29. }
  30. var fsize = $('#imageInput')[0].files[0].size; //get file size
  31. var ftype = $('#imageInput')[0].files[0].type; // get file type
  32. //allow only valid image file types
  33. switch(ftype)
  34. {
  35. case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
  36. break;
  37. default:
  38. $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
  39. return false
  40. }
  41. //Allowed file size is less than 1 MB (1048576)
  42. if(fsize>1048576)
  43. {
  44. $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
  45. return false
  46. }
  47. $('#submit-btn').hide(); //hide submit button
  48. $('#loading-img').show(); //hide submit button
  49. $("#output").html("");
  50. }
  51. else
  52. {
  53. //Output error to older unsupported browsers that doesn't support HTML5 File API
  54. $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
  55. return false;
  56. }
  57. }
  58. //function to format bites bit.ly/19yoIPO
  59. function bytesToSize(bytes) {
  60. var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  61. if (bytes == 0) return '0 Bytes';
  62. var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  63. return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
  64. }
  65. </script>

processupload.php

PHP Code

  1. <?php
  2. if(isset($_POST))
  3. {
  4. ############ Edit settings ##############
  5. $ThumbSquareSize = 200; //Thumbnail will be 200x200
  6. $BigImageMaxSize = 500; //Image Maximum height or width
  7. $ThumbPrefix = "thumb_"; //Normal thumb Prefix
  8. $DestinationDirectory = '../upload/'; //specify upload directory ends with / (slash)
  9. $Quality = 90; //jpeg quality
  10. ##########################################
  11. //check if this is an ajax <a href="/tags.php/request/" target="_blank">request</a>
  12. if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
  13. die();
  14. }
  15. // check $_FILES['ImageFile'] not empty
  16. if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
  17. {
  18. die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
  19. }
  20. // Random number will be added after image name
  21. $RandomNumber = rand(0, 9999999999);
  22. $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
  23. $ImageSize = $_FILES['ImageFile']['size']; // get original image size
  24. $TempSrc = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
  25. $ImageType = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
  26. //Let's check allowed $ImageType, we use PHP SWITCH statement here
  27. switch(strtolower($ImageType))
  28. {
  29. case 'image/png':
  30. //Create a new image from file
  31. $CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
  32. break;
  33. case 'image/gif':
  34. $CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
  35. break;
  36. case 'image/jpeg':
  37. case 'image/pjpeg':
  38. $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
  39. break;
  40. default:
  41. die('Unsupported File!'); //output error and exit
  42. }
  43. //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
  44. //Get first two values from image, width and height.
  45. //list assign svalues to $CurWidth,$CurHeight
  46. list($CurWidth,$CurHeight)=getimagesize($TempSrc);
  47. //Get file extension from Image name, this will be added after random name
  48. $ImageExt = <a href="/tags.php/substr/" target="_blank">substr</a>($ImageName, strrpos($ImageName, '.'));
  49. $ImageExt = str_replace('.','',$ImageExt);
  50. //remove extension from filename
  51. $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
  52. //Construct a new name with random number and extension.
  53. $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
  54. //set the Destination Image
  55. $thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
  56. $DestRandImageName = $DestinationDirectory.$NewImageName; // Image with destination directory
  57. //Resize image to Specified Size by calling resizeImage function.
  58. if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
  59. {
  60. //Create a square Thumbnail right after, this time we are using cropImage() function
  61. if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
  62. {
  63. echo 'Error Creating thumbnail';
  64. }
  65. /*
  66. We have succesfully resized and created thumbnail image
  67. We can now output image to user's browser or store information in the database
  68. */
  69. echo '<table width="100%" cellpadding="4" cellspacing="0">';
  70. echo '<tr>';
  71. echo '<td align="center"><img src="../upload/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail"></td>';
  72. echo '</tr><tr>';
  73. echo '<td align="center"><img src="../upload/'.$NewImageName.'" alt="Resized Image"></td>';
  74. echo '</tr>';
  75. echo '</table>';
  76. /*
  77. // Insert info into database table!
  78. mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
  79. VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
  80. */
  81. }else{
  82. die('Resize Error'); //output error
  83. }
  84. }
  85. // This function will proportionally resize image
  86. function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
  87. {
  88. //Check Image size is not 0
  89. if($CurWidth <= 0 || $CurHeight <= 0)
  90. {
  91. return false;
  92. }
  93. //Construct a proportional size of new image
  94. $ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
  95. $NewWidth = ceil($ImageScale*$CurWidth);
  96. $NewHeight = ceil($ImageScale*$CurHeight);
  97. $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
  98. // Resize Image
  99. if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
  100. {
  101. switch(strtolower($ImageType))
  102. {
  103. case 'image/png':
  104. imagepng($NewCanves,$DestFolder);
  105. break;
  106. case 'image/gif':
  107. imagegif($NewCanves,$DestFolder);
  108. break;
  109. case 'image/jpeg':
  110. case 'image/pjpeg':
  111. imagejpeg($NewCanves,$DestFolder,$Quality);
  112. break;
  113. default:
  114. return false;
  115. }
  116. //Destroy image, frees memory
  117. if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
  118. return true;
  119. }
  120. }
  121. //This function cor<a href="/fw/photo.html" target="_blank">ps</a> image to create exact square images, no matter what its original size!
  122. function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
  123. {
  124. //Check Image size is not 0
  125. if($CurWidth <= 0 || $CurHeight <= 0)
  126. {
  127. return false;
  128. }
  129. //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
  130. if($CurWidth>$CurHeight)
  131. {
  132. $y_offset = 0;
  133. $x_offset = ($CurWidth - $CurHeight) / 2;
  134. $square_size = $CurWidth - ($x_offset * 2);
  135. }else{
  136. $x_offset = 0;
  137. $y_offset = ($CurHeight - $CurWidth) / 2;
  138. $square_size = $CurHeight - ($y_offset * 2);
  139. }
  140. $NewCanves = imagecreatetruecolor($iSize, $iSize);
  141. if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
  142. {
  143. switch(strtolower($ImageType))
  144. {
  145. case 'image/png':
  146. imagepng($NewCanves,$DestFolder);
  147. break;
  148. case 'image/gif':
  149. imagegif($NewCanves,$DestFolder);
  150. break;
  151. case 'image/jpeg':
  152. case 'image/pjpeg':
  153. imagejpeg($NewCanves,$DestFolder,$Quality);
  154. break; //phpfensi.com
  155. default:
  156. return false;
  157. }
  158. //Destroy image, frees memory
  159. if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
  160. return true;
  161. }
  162. }

以上就是我们要介绍的ajax无刷新图片上传功能了,其实就是通过异步模式提交给php然后由php上传图片并且生成小图返回给指定的id的htm元素模块即可.