Асинхронная загрузка файлов с помощью ajax

Пример приложения, использующего встроенные фреймы для загрузки файла. (как в популярных файлообмениках, например RapidShare, Megaupload)

Следующие функции используются в данном примере:

  • move_uploaded_file - Перемещает загруженный файл в новое место
  • fopen - открывает файл
  • fwrite - записывает в открытый файл
  • fclose - закрывает файл
  • str_replace - заменяет строку поиска на строку замены
  • filesize - возвращает размер файла в байтах
  • filemtime - возвращает время последней модификации файла
code: #php
  1. <?php
  2. $upload_dir = "/var/www/files/aeu"; // Directory for file storing
  3.                                             // filesystem path
  4.  
  5. $web_upload_dir = "/aeu"; // Directory for file storing
  6.                           // Web-Server dir
  7.  
  8. /* upload_dir is filesystem path, something like
  9.    /var/www/htdocs/files/upload or c:/www/files/upload
  10.  
  11.    web upload dir, is the webserver path of the same
  12.    directory. If your upload-directory accessible under
  13.    www.your-domain.com/files/upload/, then
  14.    web_upload_dir is /files/upload
  15. */
  16.  
  17.  
  18. // testing upload dir
  19. // remove these lines if you're shure
  20. // that your upload dir is really writable to PHP scripts
  21. $tf = $upload_dir.'/'.md5(rand()).".test";
  22. $f = @fopen($tf, "w");
  23. if ($f == false)
  24.     die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
  25.        or something like this");
  26. fclose($f);
  27. unlink($tf);
  28. // end up upload dir testing
  29.  
  30.  
  31.  
  32. // FILEFRAME section of the script
  33. if (isset($_POST['fileframe']))
  34. {
  35.     $result = 'ERROR';
  36.     $result_msg = 'No FILE field found';
  37.  
  38.     if (isset($_FILES['file']))  // file was send from browser
  39.     {
  40.         if ($_FILES['file']['error'] == UPLOAD_ERR_OK)  // no error
  41.         {
  42.             $filename = $_FILES['file']['name']; // file name
  43.             move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
  44.             // main action -- move uploaded file to $upload_dir
  45.             $result = 'OK';
  46.         }
  47.         elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
  48.             $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
  49.         else
  50.             $result_msg = 'Unknown error';
  51.  
  52.         // you may add more error checking
  53.         // see http://www.php.net/manual/en/features.file-upload.errors.php
  54.         // for details
  55.     }
  56.  
  57.     // outputing trivial html with javascript code
  58.     // (return data to document)
  59.  
  60.     // This is a PHP code outputing Javascript code.
  61.     // Do not be so confused ;)
  62.     echo '<html><head><title>-</title></head><body>';
  63.     echo '<script language="JavaScript" type="text/javascript">'."\n";
  64.     echo 'var parDoc = window.parent.document;';
  65.     // this code is outputted to IFRAME (embedded frame)
  66.     // main page is a 'parent'
  67.  
  68.     if ($result == 'OK')
  69.     {
  70.         // Simply updating status of fields and submit button
  71.         echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';
  72.         echo 'parDoc.getElementById("filename").value = "'.$filename.'";';
  73.         echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';
  74.         echo 'parDoc.getElementById("upload_button").disabled = false;';
  75.     }
  76.     else
  77.     {
  78.         echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';
  79.     }
  80.  
  81.     echo "\n".'</script></body></html>';
  82.  
  83.     exit(); // do not go futher
  84. }
  85. // FILEFRAME section END
  86.  
  87.  
  88.  
  89. // just userful functions
  90. // which 'quotes' all HTML-tags and special symbols
  91. // from user input
  92. function safehtml($s)
  93. {
  94.     $s=str_replace("&", "&amp;", $s);
  95.     $s=str_replace("<", "&lt;", $s);
  96.     $s=str_replace(">", "&gt;", $s);
  97.     $s=str_replace("'", "&apos;", $s);
  98.     $s=str_replace("\"", "&quot;", $s);
  99.     return $s;
  100. }
  101.  
  102. if (isset($_POST['description']))
  103. {
  104.     $filename = $_POST['filename'];
  105.     $size = filesize($upload_dir.'/'.$filename);
  106.     $date = date('r', filemtime($upload_dir.'/'.$filename));
  107.     $description = safehtml($_POST['description']);
  108.  
  109.     // Let's generate file information page
  110. $html =<<<END
  111. <html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>
  112. <body>
  113. <h1>{$filename}</h1>
  114. <p>This is a file information page for your uploaded file. Bookmark it, or send to anyone...</p>
  115. <p>Date: {$date}</p>
  116. <p>Size: {$size} bytes</p>
  117. <p>Description:
  118. <pre>{$description}</pre>
  119. </p>
  120. <p><a href="{$web_upload_dir}/{$filename}" style="font-size: large;">download file</a><br>
  121. <a href="{$PHP_SELF}" style="font-size: small;">back to file uploading</a><br>
  122. <a href="{$web_upload_dir}/upload-log.html" style="font-size: small;">upload-log</a></p>
  123. <br><br>
  124. </body></html>
  125. END;
  126.     // save HTML
  127.     $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
  128.     fwrite($f, $html);
  129.     fclose($f);
  130.     $msg = "File {$filename} uploaded,
  131.           <a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";
  132.  
  133.     // Save to file upload-log
  134.     $f = fopen($upload_dir."/upload-log.html", "a");
  135.     fwrite($f, "<p>$msg</p>\n");
  136.     fclose($f);
  137.  
  138.     // setting result message to cookie  
  139.     setcookie('msg', $msg);
  140.     // redirecting to the script main page
  141.     // we're doing so, to avoid POST form reposting  
  142.     // this method of outputting messages is called 'flash' in Ruby on Rails  
  143.     header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
  144.     exit();
  145.     // redirect was send, so we're exiting now
  146. }
  147.  
  148. // retrieving message from cookie
  149. if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')  
  150. {  
  151.     if (get_magic_quotes_gpc())
  152.         $msg = stripslashes($_COOKIE['msg']);
  153.     else
  154.         $msg = $_COOKIE['msg'];
  155.  
  156.     // clearing cookie, we're not going to display same message several times
  157.     setcookie('msg', '');
  158. }
  159. ?>
  160. <!-- Beginning of main page -->
  161. <html><head>
  162. <title>IFRAME Async file uploader example</title>
  163. </head>
  164. <body>
  165. <?php
  166. if (isset($msg)) // this is special section for outputing message
  167.     echo '<p style="font-weight: bold;">'.$msg.'</p>';
  168. ?>
  169. <h1>Upload file:</h1>
  170. <p>File will begin to upload just after selection. </p>
  171. <p>You may write file description, while you file is being uploaded.</p>
  172.  
  173. <form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
  174. <input type="hidden" name="fileframe" value="true">
  175. <!-- Target of the form is set to hidden iframe -->
  176. <!-- From will send its post data to fileframe section of
  177.      this PHP script (see above) -->
  178.  
  179. <label for="file">text file uploader:</label><br>
  180. <!-- JavaScript is called by OnChange attribute -->
  181. <input type="file" name="file" id="file" onChange="jsUpload(this)">
  182. </form>
  183. <script type="text/javascript">
  184. /* This function is called when user selects file in file dialog */
  185. function jsUpload(upload_field)
  186. {
  187.     // this is just an example of checking file extensions
  188.     // if you do not need extension checking, remove
  189.     // everything down to line
  190.     // upload_field.form.submit();
  191.  
  192.     var re_text = /\.txt|\.xml|\.zip/i;
  193.     var filename = upload_field.value;
  194.  
  195.     /* Checking file type */
  196.     if (filename.search(re_text) == -1)
  197.     {
  198.         alert("File does not have text(txt, xml, zip) extension");
  199.         upload_field.form.reset();
  200.         return false;
  201.     }
  202.  
  203.     upload_field.form.submit();
  204.     document.getElementById('upload_status').value = "uploading file...";
  205.     upload_field.disabled = true;
  206.     return true;
  207. }
  208. </script>
  209. <iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
  210. </iframe>
  211. <!-- For debugging purposes, it's often useful to remove
  212.      "display: none" from style="" attribute -->
  213.  
  214. <br>
  215. Upload status:<br>
  216. <input type="text" name="upload_status" id="upload_status"
  217.        value="not uploaded" size="64" disabled>
  218. <br><br>
  219.  
  220. File name:<br>
  221. <input type="text" name="filenamei" id="filenamei" value="none" disabled>
  222.  
  223. <form action="<?=$PHP_SELF?>" method="POST">
  224. <!-- one field is "disabled" for displaying-only. Other, hidden one is for
  225.     sending data -->
  226. <input type="hidden" name="filename" id="filename">
  227. <br><br>
  228.  
  229. <label for="photo">File description:</label><br>
  230. <textarea rows="5" cols="50" name="description"></textarea>
  231.  
  232. <br><br>
  233. <input type="submit" id="upload_button" value="save file" disabled>
  234. </form>
  235. <br><br>
  236. <a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>
  237. <br><br><br>
  238.  
  239. Example by <a href="http://samplecode.ru/">SampleCode</a>
  240. </body>
  241. </html>
Поделиться:

Похожие статьи: