uploading a file via ajax with php
I would like to know if it is possible to upload a binary file via ajax and php, and have a link to download it. I would like to avoid refreshing the entire page, as with a standard html form. So far I have been using forms to get information, such as radio and text boxes, and using javascript to override the default behavior. Is a similar thing possible for uploading a file?
It isn't possible to submit a file through Javascript.
Your options are:
- The hidden iframe trick, popularized by Google. Implementing this yourself can result in some klunky stuff so there are libraries out there, such as jQuery, which have plugins, such as jQuery's popular Form Plugin, that automate this so you don't have to feel dirty inside when using it.
- Using Flash to faciliate the process. Most notably SWFUpload is very popular. All things being equal, I'd probably go with the Javascript solution over this, but I've used this in the past with success. The cool thing about this solution is that it comes with a nicer interface such as loading indicators and thumbnails and such. At this point, though, you're asking for a user to have Flash + Javascript available, which may not work in some situations.
- Using Silverlight instead of Flash, although I wouldn't really consider this as a viable solution, as it has a much lower penetration rate than the other two solutions.
While you can't upload a file via AJAX, you can put a file control in a popup and then update the page that spawned the popup when it closes.
I'm not too clear on how to update the page that spawned the popup, but I've seen it done in the ANGEL Learning Management Suite.
Have an IFrame (display:none) on your form and set your form's target to be that iframe.
My form looks like this:
<iframe id="upload_target" name="upload_target" src="" style="width:0px;height:0px;border:0px solid #fff;"></iframe>
<form enctype="multipart/form-data" name="frmXMLUpload" target="upload_target" action="scripts/uploadXML.php" method="POST" onSubmit="return checkExtension(fXMLFile.value, 'xml')">
<!--only allow up to 30k of data to be uploaded-->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input name="fXMLFile" id="fXMLFile" type="file" accept="text/xml" size="50" />
<p><input type="submit" value="Upload" /></p>
</form>
And deal with response in yuor IFRAME. basically this is not AJAX at all, but who would like JavaScript to have access to files on your local computer? It's fine the way it is.