Ajax File Upload Tutorial

Tagged:  

As you are writing an Ajax application, you may want to allow users to upload files through an Ajax form. The folks over at AnyExample.com have put together a good tutorial on the subject. The tutorial uses PHP for the back end, but the principal is the same for any server side language.

Below is an excerpt from the tutorial.

How IFRAME file uploading works?

  • There is a simple <form... which contains only <input type="file" ... > field.
    Target for this form is a hidden IFRAME (with "display: none;" CSS style) and
    OnChange event for the file field is set to JavaScript function which checks file extension (optional for this example, but
    very useful in general) and submits form.
  • Special part of the script (marked FILEFRAME, see comments) saves file upload, checks for uploading errors and outputs JavaScript code to that
    hidden IFRAME.
    The javascript code uses parent.window.document object, which allows to modify parent document (visible page, which users is viewing).
    It sets filename value and enables submit button on the other form using getElementById method.
  • The other form has 'description' text-field and hidden field 'filename'. User may fill 'description' field while file is uploading.
    When file uploading is finished, user press submit and "file information" page is generated (based on filename from hidden field and user's
    file description).

Possible drawback of this method is file garbage: files are uploaded even if user does not press submit button. You may need to write 'garbage file
collector' which will delete any unused file.

This example stores all uploaded file in filesystem folder. You need to specify it at the beginning of script, see variables $upload_dir and
$web_upload_dir. There is fail-checking which checks whether it is possible to write create files in upload directory.

We use following functions in this example:

PHP

  • move_uploaded_file - move file uploaded to web server
  • fopen - open file
  • fwrite - write to opened file
  • fclose - close file
  • str_replace - replace one substring by another
  • filesize - returns file size in bytes
  • filemtime - returns file modification time

You can read the full post here.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <div> <blockquote> <object> <embed> <img> <param>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Copy the characters (respecting upper/lower case) from the image.