Today's Question:  What does your personal desk look like?        GIVE A SHOUT

How to Asynchronously Upload Files Using HTML5 and Ajax

  Craig Buckler        2011-10-29 13:45:00       10,082        0    

In my previous posts, we discovered How to Use HTML5 File Drag & Drop, and Open Files Using HTML5 and JavaScript. Now we have a valid set of files, it possible to upload each one to the server. The process occurs asynchronously in the background so the user can complete other on-page tasks while it occurs.

The HTML

Let’s examine our HTML form again:

  1. <form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">  
  2. <fieldset>  
  3. <legend>HTML File Upload</legend>  
  4. <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />  
  5. <div>  
  6.     <label for="fileselect">Files to upload:</label>  
  7.     <input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />  
  8.     <div id="filedrag">or drop files here</div>  
  9. </div>  
  10. <div id="submitbutton">  
  11.     <button type="submit">Upload Files</button>  
  12. </div>  
  13. </fieldset>  
  14. </form>  

We’ll be uploading files to a PHP page, upload.php. The page will handle both the Ajax upload requests and standard form POSTs when the user clicks “Upload Files”.

Our JavaScript will ensure that only JPG images are uploaded which are smaller than 300,000 bytes — the value specified in MAX_FILE_SIZE.

The JavaScript

First, we require an additional line within our FileSelectHandler() function which is called when one or more files is chosen or dropped. Within our File loop, we’ll call an additional function — UploadFile():

  1. // file selection  
  2. function FileSelectHandler(e) {  
  3.     // cancel event and hover styling  
  4.     FileDragHover(e);  
  5.     // fetch FileList object  
  6.     var files = e.target.files || e.dataTransfer.files;  
  7.     // process all File objects  
  8.     for (var i = 0, f; f = files[i]; i++) {  
  9.         ParseFile(f);  
  10.         UploadFile(f);  
  11.     }  
  12. }  

File uploading requires the XMLHttpRequest2 object which is currently available in Firefox and Chrome. Before we make the Ajax call, we ensure an .upload() method is available and that we have a JPG with a file size less than the MAX_FILE_SIZE form value:

  1. // upload JPEG files  
  2. function UploadFile(file) {  
  3.     var xhr = new XMLHttpRequest();  
  4.     if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {  

The XMLHttpRequest .open() method is set to POST data to upload.php, the action attribute of our upload form. In addition, we set an HTTP header to the file’s name and pass the File object to the .send() method:

  1.     // start upload  
  2.     xhr.open("POST", $id("upload").action, true);  
  3.     xhr.setRequestHeader("X_FILENAME", file.name);  
  4.     xhr.send(file);  
  5. }  

The PHP

Our PHP file, upload.php, now checks for the X_FILENAME HTTP header to differentiate between Ajax requests and standard form POSTs:

  1. <?php  
  2. $fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);  

If a filename has been set, PHP can retrieve the posted data and output it to a new file in an ‘uploads’ folder. Amazingly, this can be achieved in a single line of code:

  1. if ($fn) {  
  2.     // AJAX call  
  3.     file_put_contents(  
  4.         'uploads/' . $fn,  
  5.         file_get_contents('php://input')  
  6.     );  
  7.     echo "$fn uploaded";  
  8.     exit();  
  9. }  

Standard HTML multipart/form-data posts can be handled using the usual PHP $_FILE functions:

  1. else {  
  2.     // form submit  
  3.     $files = $_FILES['fileselect'];  
  4.     foreach ($files['error'] as $id => $err) {  
  5.         if ($err == UPLOAD_ERR_OK) {  
  6.             $fn = $files['name'][$id];  
  7.             move_uploaded_file(  
  8.                 $files['tmp_name'][$id],  
  9.                 'uploads/' . $fn  
  10.             );  
  11.             echo "<p>File $fn uploaded.</p>";  
  12.         }  
  13.     }  
  14. }  

You can view the demonstration page, however, please note it is hosted on a server without PHP support and the upload will not occur. Therefore, please download the files to examine the code and install it on your own PHP server.

The code above will work, but the user won’t know whether a file upload has started, finished or failed. You need to read the final instalment in this series: How to Create File Upload Progress Bars in HTML5 and JavaScript…

Source:http://www.sitepoint.com/html5-ajax-file-upload/

AJAX  FILE UPLOAD  HTML5  ASYNCHRONOUSLY  X-FILENAME 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.