Wednesday

AJAX File Uploads (using Dojo and PHP)

Slashdot

It is easy to upload files using Ajax and PHP. How? I'll try to explain below.

We'll be using some common sense, Dojo Framework for AJAX, HTML, Apache, Javascript, and PHP. Make sure you install Apache and PHP (read other tutorials for that). I'll explain how to setup Dojo (for this tutorial) below. But before we proceed please read and understand the disclaimer below.

DISCLAIMER: I have made every attempt to present accurate information, but I cannot guarantee that inaccuracies will not occur. I (the author) will not be held responsible for any claim, loss, damage or inconvenience caused as a result of any information found on this website (blog).

Make sure you configure PHP to allow file uploads.
  • Fire up your browser and go to http://dojotoolkit.org/. Download Dojo form the website. I've used version 0.4.1 for this tutorial.
  • After downloading the zip file go to the folder where you want to put your file upload code (I've named this file index.php). Unzip the downloaded file in that folder and rename the new folder created (e.g. dojo-0.4.1-ajax.zip) to dojo.
  • Enter the code below in the head (between <head> and </head>) section of your HTML file (that contains file upload form). I'm naming it index.php.

<script language="javascript" type="text/javascript" src="./dojo/dojo.js"></script>

  • Now in the body of the index.php enter the form as follows.
<form id="upload_file" action="file_upload_script.php" method="post"
enctype="multipart/form-data">

<input type="hidden" name="MAX_FILE_SIZE" value="8388608" />
<input type="file" name="select_file" tabindex="1" size="35" />
<input type="button" value="Submit" onClick="upload_file_submit()" tabindex="2">
</form>

For the sake of simplicity I am using a very simple form. You can add more fields if you want.

  • Now, enter the javascript code below in your head section of index.php.

<script language="javascript">
<!--
// Dojo configuration and Variable Initialization
// Put this code in index.php before the line where you include the javascript for dojo
// djConfig = { isDebug: true };
dojo.require("dojo.io.*");
dojo.require("dojo.io.IframeIO");
ctr = 0;
function upload_file_submit()
{

var bindArgs = {

formNode: document.getElementById("upload_file"), // form's id
mimetype: "text/plain", // Enter file type info here
content:
{
increment: ctr++,
name: "select_file", // file name in the form
post_field: "" // add more fields here .. fields will be accessible through $_POST["psot_fields"]
},
handler: function(type, data, evt)
{
// handle successful response here
if(type == "error") alert("Error occurred. ");
else
{
// getting error message from PHP's file upload script
res = dojo.byId("dojoIoIframe").contentWindow.document.getElementById("output").innerHTML;
// Incase of an error, display the error message
if(res != "true") alert(res);
else alert("File uploaded successfully.");
}
}
};
var request = dojo.io.bind(bindArgs);
}

//-->
</script>

  • Now, create a file named file_upload_script.php and add the code below in that file.

<script language="php">
// You can send any message to javascript client using die(create_message(<message>)); ...
//this function will terminate the script and will return control to the client

if( isset($_POST["MAX_FILE_SIZE"]) && isset($_FILES))

{
if( $_FILES['select_file']['size'] > $_POST["MAX_FILE_SIZE"])
die(create_message("File size must be less than ".$_POST["MAX_FILE_SIZE"]." bytes."));

$uploadFile = "./file_name_on_server.txt";

if(move_uploaded_file( $_FILES['select_file']['tmp_name'], $uploadFile))
{
$fp = fopen ($uploadFile, "rb");
if(!$fp) die(create_message("Error opening uploaded file."));
fclose($fp);
// SENDING TRUE IS MANDATORY SO THAT THE JAVASCRIPT

//FUNCTION KNOWS THAT THE FILE HAS BEEN UPLOADED PROPERLY
die(create_message("true"));
}
else die(create_message( $_FILES['select_file']['tmp_name']." could not be uploaded successfully."));

}
else die(create_message( "Error in form input: Data is missing. "));

function create_message($string)

{
$output = "";
$output .= "<html><head></head><body>";
$output .= "<textarea id=\"output\">";
$output .= trim($string);
$output .= "</textarea>";
$output .= "</body></html>";
return $output;
}
</script>


That's it. Go to index.php from your browser and upload a text file. Press submit. If there is no error you should see File uploaded successfully message.

Labels: , , , , ,

6 Comments:

At May 5, 2008 at 3:17:00 AM PDT , Anonymous Anonymous said...

Its not working yaar please check it gives javascrit error

 
At July 14, 2008 at 1:52:00 PM PDT , Blogger Unknown said...

Hmmmm... Looks easy enough... I can choose a file, but when I click submit nothing happens... No errors... No file uploaded... Any ideas? Thanks!

 
At July 14, 2008 at 1:52:00 PM PDT , Blogger Unknown said...

Hmmmm... Looks easy enough... I can choose a file, but when I click submit nothing happens... No errors... No file uploaded... Any ideas? Thanks!

 
At August 13, 2008 at 2:34:00 PM PDT , Anonymous Anonymous said...

This dojo require statement doesn't work on my installation:

dojo.require("dojo.io.*");

I saw the error message using Firebug with Firefox.

 
At January 7, 2009 at 6:36:00 PM PST , Anonymous Anonymous said...

r.e. "dojo.io.bind(bindArgs);" - this function does not exit.

 
At April 7, 2009 at 6:38:00 PM PDT , Blogger spw2000 said...

LOOKs easy and the description is great BUT how do I control where the uploaded file goes???

Also, in my limited understanding of the DOJO framework, is thre not supposed to be an ajax compoenent that I creat on the server that will assist me in saving the file to a desired location???

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home