Gorilla3D Primative Teachings

Joseph Says: STOP SPAMMING MY %$#@ING SITE $%#@!!!!!
Search

PHP & Firefox 3 AJAX Image Upload


Friday, August 15, 2008

PHP + Firefox3 AJAX Image Upload

Here is a sample dump of using firefox3's getAsDataURL to push to php and using GD to process it into an image and then save to file.

  1.  
  2. /* Ajax Functions */
  3. function Ajax(url, options) {
  4. if (typeof XMLHttpRequest!='undefined') {var page = new XMLHttpRequest();}
  5. else if (window.createRequest) { var page = window.createRequest();}
  6. else if (window.ActiveXObject) { var page = new ActiveXObject('MSXML2.XMLHTTP.3.0');}
  7. else { alert('Ooops, we failed to process your request. Tell us your browser please!'); }
  8. if (page) {
  9. if (options.method == 'post') {
  10. page.open('POST', url, true);
  11. page.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded") }
  12. else {
  13. page.open('GET', url, true);
  14. }
  15. page.onreadystatechange = function() {
  16. if (page.readyState == 4 && page.status == 200) {
  17. if ('function' == typeof options.onComplete) options.onComplete(page.responseText);
  18. }
  19. }
  20. if (options.method == 'post') {
  21. page.send(options.data);
  22. } else {
  23. page.send(null);
  24. }
  25. } else {
  26. alert('There has been a problem processing your request');
  27. }
  28. }
  29. function writeImage() {
  30. var imgdata = $('imagefile').files.item(0).getAsDataURL();
  31. var imgsize = $('imagefile').files.item(0).fileSize;
  32. var imgname = $('imagefile').files.item(0).fileName;
  33. Ajax("post.image.php", {"method":"post", "data": {"data":imgdata, "size":imgsize, "name":imgname}, "onComplete": function(image) { alert('uploaded'); }});
  34. }
  35.  


  1.  
  2. <input type="file" id="imagefile" name="imagefile" onchange="writeImage()"/>
  3.  


  1.  
  2. <?php
  3. $uploadfile = 'temp.jpg';
  4. //-- Parse the data
  5. $img_str = $_POST['data'];
  6. $img_str = explode('base64,', $img_str);
  7. $img_str = $img_str[1];
  8. $img_str = base64_decode($img_str);
  9. //-- Create image from string
  10. $image = imagecreatefromstring($img_str);
  11. //-- Save to file
  12. imagejpeg($image, $uploadfile, 85);
  13. ?>
  14.  

Comments


No comments

Add Comment