AJAX file uploads

+ 
Laravel

Problem:




XMLHttpRequest support 
not consistent in various browsers
Image processing in the browser is even worse

''You're killin me, IE'' - rubbish


For uploads:
  • Use hidden iFrame for IE < 10
  • Use Flash for older versions of browsers
  • Use XMLHttpRequest for newer browsers
 
For image processing:
  • Use Flash
  • Use canvas + blob

Solutions:

Front end

Back end
  • Store directly
  • Use S3
  • Use Flysystem package

Mailru/FileAPI = my favorite


  • Supports HTML 5 features
  • Falls back on Flash for older browsers
  • Superb image processing capabilities
  • Has jQuery plugin (wrapper)
  • Totally free with no strings attached

Read case study on SmashingMagazine

Security


  • CSRF token
  • MIME validation
  • File names
  • Protect Uploads folder and temp folder
  • Delete temp files (cron job)

How to 

  1. Upload to temp folder + return file name back as JSON
  2. File name is stored in hidden input field
  3. On form submission move the file to 
    permanent location if validation passes
  4. Run a cron job to clean up temp folder every X minutes
 $now = time();
 foreach(File::directories('public/uploads/temp') as $dir ){
    $dirtime = filemtime($dir);
            
    if( $now-$dirtime > 3600){
      File::deleteDirectory($dir);
      $this->info('Directory '.$dir.' was deleted');
    }
}

Resources






Thanks!

AJAX file uploads

By msurguy

AJAX file uploads

  • 2,402