Unfortunatly we only lhave a few ways to upload files without reloading the whole page. You can do this by using an iframe, flash or through a java applet. Since applets support drag and drop, we can use it to create a drag and drop file uploader.
This is the html to hold the java applet. We chuck in a text field so we can pass additional information with the applet’s file post.
<input id="meta-text" />
<button onclick="javascript:document.applets.uploadApplet.setMetadata(document.getElementById('meta-text').value);">Set metadata</button>
<br />
<applet type="application/x-java-applet" name="uploadApplet" id="uploadApplet" code="dndapplet/applet/DNDApplet" archive="signed_dndapplet.jar" mayscript="true" scriptable="true">
<param name="uploadPath" value="uploader.php">
<param name="funcNameHandleCurrentUpload" value="handleCurrentUpload">
</applet>
When a file is draged and dropped into the applet, it submits the file to the location passed through the uploadPath param. The upload works the same way as any FILE/POST form submit. So we write some PHP to handle it and return how the upload went.
$uploadPath = "./uploads";
$maxfilesize = 30000; //kByte
$tmp_name = $_FILES['uploadfile']['tmp_name'];
$file_name = $_FILES['uploadfile']['name'];
$tgt_path = "$uploadPath/$file_name";
$field_name = 'uploadfile';
if ($_FILES['uploadfile']['size'] > $maxfilesize*1024)
die ("File exceeds maximum filesize: $maxfilesize kByte.");
if ( ! is_writable( $uploadPath) )
die ("Upload path is not writeable.");
if ( ! move_uploaded_file( $tmp_name, $tgt_path ) )
die ("Problem during upload.");
echo "$file_name Upload successful. Metadata: " . $_POST['metadata'];
Finally, we have to go back to the html page and write some javascipt to handle the value returned by the applet.
function javascript_callback (return_str)
{ alert(return_str);
}
Now we are all done. You can download the demo and the source code live demo link . If you want to change the appearance of the applet, you can edit the code .
Here’s the live demo link and the full source code
August 7th, 2009 at 10:35 am
You absolutely can do AJAX uploads with Javascript – you don’t need extras like iframes, Java, or Flash. (Not drag-and-drop, of course)
Two examples:
http://www.phpletter.com/Our-Projects/AjaxFileUpload/
http://tomas.epineer.se/archives/3
Why use iframes, or Java/Flash (which require extra plugins to be installed), when they’re not necessary?
August 7th, 2009 at 12:40 pm
Hi Jordan,
I think you missed the “drag and drop” part of the title. Also XHR doesn’t support file uploads. (your second link says just this: “Since the XMLHttpRequest object doesn’t support file uploads, this had to be done using iframes. “)
September 2nd, 2010 at 5:23 pm
Hello, My name is William Foo and I am now in North Carolina. I hope someone has seen any resource that is quite the same as this ESL instructional site. I have no budget whatsoever, appreciate if you let me have the link to any such free resource. Write me.