Safari File Upload Hang Up

The HTML Form file input tag has been around for ages but for some reason Safari has had native issues with it since the dawn of the Mac era. I always expect there to be issues that arise in every project but this was certainly was a surprise that put me through the early hours of the night before final client testing.

An Ajax hack is required to force Safari to close the keep alive requests which is better explained by techies at Webkit Bugzilla. The hang effect is basically Safari continuing to show it’s uploading a file and never going anywhere. Sometimes the file will work and go through, especially smaller sizes.

Solutions varied on closing keepalive, telling Safari to move it. Airblade Software offers a good solution which is expanded by this freelancer forum I visited. The script requires Ajax and the forum suggested using the Prototype framework’s Ajax support but that would create conflicts with my existing jQuery code so I grabbed the simple Ajax Request Library by Matt Kruse.  As well, a forum user notes you should call the script before the form, thus document ready is added.

In your body’s form, include onsubmit to the kill function.

<form action="upload.php" enctype="multipart/form-data" method="post" onsubmit="closeKeepAlive();">
<input type="file" name="image" />
<input type="submit" id="upload" name="upload" value="Send " />
</form>

In the head:

<script type="text/javascript" src="js/ajaxrequest.js"></script>
<script type="text/javascript">
/* die safari! */
$(document).ready(function () { 
function closeKeepAlive() {
  if (/AppleWebKit|MSIE/.test(navigator.userAgent)) {
    new Ajax.Request("safari-die.php", { asynchronous:false });	
  }
return true;
}
});
</script>

In the php file

<?php header("connection: close"); ?>