How to make an instant conclusion when uploading a photo so that the photo that the person has uploaded is shown, in short, an example when changing the avatar of Vkontakte.

  • and how .load () will show the picture? request a block with a picture separately? Is not it easier to change the src preview? - zb '

1 answer 1

I do not know how Vkontakte is done there, but I hope that your task is understood correctly. In the example, I did not go deep and did schematically. In real life, you will need to process data, screen, check the extension of downloaded files and other dangers.

Create three files and place in one directory:

  • index.php (or index.html)
  • handler.php
  • script.js
  • and folder "avatars"

index.php (connect the jQuery and script.js library to it). In <body> we write:

<iframe name="tFrame" style="display:none;"></iframe> <form action="handler.php" method="post" enctype="multipart/form-data" target="tFrame"> <input type="file" id="user_avatar" name="user_avatar" /> <input type="hidden" name="user_id" value="100500" /> </form> <div id="avatar"> <img src="./avatars/no_avatar.png" style="max-width: 256px; max-height: 256px;" alt="" /> </div> 


 <?php if(isset($_POST['user_id'])){ $success = false; if($_FILES['user_avatar']['error'] == 0){ $uid = (int)$_POST['user_id']; $ext = explode('.',$_FILES['user_avatar']['name']); $file_name = 'avatar_'.$uid.'.'.$ext[1]; // новое имя файла $path_orig = './avatars/original/'.$file_name; // путь к оригиналу $path_thumg = './avatars/thumbs/'.$file_name; // путь к миниатюре if(move_uploaded_file($_FILES['user_avatar']['tmp_name'],$path_orig)){ require('image.class.php'); // true - сохранять пропорции, false - не сохранять $image = new Imagethumb($path_orig, true); // 250, 250 - размеры миниатюры // При сохранении пропорций - как max-width, max-height $image->getThumb($path_thumg, 250, 250); $success = true; } } echo '<script type="text/javascript">window.parent.onResponse('.$success.',"'.$path_thumg.'");</script>'; } ?> 


 $(document).ready(function(e) { $('#user_avatar').change(function(){ $(this).parent('form').submit(); }); }); function onResponse(s,f){ if(s){ $('#avatar img').animate({ opacity: 0 }, function(){ $(this).attr('src',f + '?' + Math.floor(Math.random( ) * (100+1))) .animate({ opacity: 1 }); }); } else { alert('Пичалька! Аватарчик умер в дороге.'); } } 

Chavo will not be clear - ask.

UPD Regarding resizing - in the internet thousands of ready-made solutions. Find it would not be difficult. In general, place the file with the class in the same directory. In the folder avatars create two directories original and thumbs . I updated the code of the file handler.php , do not forget to do it and you.

PS To see how this miracle of hostile technology works, you can >> here <<

  • and how to add a trim here and save a copy of the photo 100x100px - avp
  • Supplemented in response - Deonis