• No results found

I suppose it is necessary to bring a little bad news to Ajax at this point; it is not possible to process a file upload through the XMLHttpRequestobject. The reason for this is that JavaScript has no access to your computer’s file system. While this is somewhat disap- pointing, there are still ways to perform Ajax-like functionality for this without making use of the XMLHttpRequestobject. Clever developers have discovered that you can use hidden iframes to post a form request, thereby allowing for a file upload without a com- plete page refresh (although you might see a bit of a screen flicker).

By setting the iframe’s CSS displayproperty to none, the element is present on the page to be utilized by the upload form, but not visible to the end user. By assigning a name

to the iframetag, you can use the targetattribute in the formtag to post the request to the

hidden iframe. Once you have the iframe configured, you can perform any uploads you like, and then use Ajax to perform any extra functionality. Consider the following exam- ple, which will allow you to upload an image to a folder of your specification. Consider the code in Listing 6-1, which will allow you to create the application shown in Figure 6-1.

Figure 6-1.An Ajax-enabled file upload system that uses hidden iframes to hide the upload

Listing 6-1.The Code to Create a Form with a Hidden Iframe for Processing

(sample6_1.html) <!-- sample6_1.html -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"➥

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Sample 6_1</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" href="style.css" />

<script type="text/javascript" src="xmlhttp.js"></script> <script type="text/javascript" src="functions.js"></script> </head>

<body>

<div id="showimg"></div>

<form id="uploadform" action="process_upload.php" method="post"➥

enctype="multipart/form-data" target="uploadframe"➥

onsubmit="uploadimg(this); return false"> Upload a File:<br />

<input type="file" id="myfile" name="myfile" /> <input type="submit" value="Submit" />

<iframe id="uploadframe" name="uploadframe" src="process_upload.php"➥

class="noshow"></iframe> </form>

</body> </html>

Listing 6-1 creates the groundwork and user interface for the application. Here, you will notice the form (with the fileelement) and the iframe it will be posting the request

into. Note the noshowclass, which is set up within the headtag of your document. The

noshowclass is what will make your iframe effectively invisible.

In order to actually process the upload, you are using a bit of Ajax-enabled JavaScript. The JavaScript to perform the upload can be found within the functions.js

file, and is a function called uploadimg. This function is called when the submit button is clicked.

//functions.js

function uploadimg (theform){ //Submit the form.

theform.submit(); }

For now, this file contains only one function (uploadimg), which will simply be used to submit your form; but as you build upon this example throughout the chapter, it will become a more crucial element in building a full Ajax structure. Once the form submits, the following PHP file (loaded into the iframe) will handle the actual file upload. Consider the PHP script in Listing 6-2.

Listing 6-2.The PHP Code Required to Upload the Image (process_upload.php)

<?php

//process_upload.php //Allowed file MIME types.

$allowedtypes = array ("image/jpeg","image/pjpeg","image/png","image/gif"); //Where we want to save the file to.

$savefolder = "images"; //If we have a valid file if (isset ($_FILES['myfile'])){

//Then we need to confirm it is of a file type we want. if (in_array ($_FILES['myfile']['type'], $allowedtypes)){

//Then we can perform the copy. if ($_FILES['myfile']['error'] == 0){

$thefile = $savefolder . "/" . $_FILES['myfile']['name'];

if (!move_uploaded_file ($_FILES['myfile']['tmp_name'], $thefile)){ echo "There was an error uploading the file.";

} else {

//Signal the parent to load the image. ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"➥

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>

<script type="text/javascript" src="functions.js"></script> </head>

<body onload="doneloading (parent,'<?=$thefile?>')"> <img src="<?=$thefile?>" /> </body> </html> <?php } } } } ?>

In this PHP code, you first create two variables that you will use to determine what type of file you want uploaded and where you want to put it. The $allowedtypesarray con- tains a listing of MIME types that you want to allow. A file’s MIME typeis a string that is used to denote the type of data the file contains. In this case, we are only allowing images of type JPEG, GIF, and PNG.

You will be saving your uploaded images to a folder on the web server, which means you need a directory that is writable by the web server. Listing 6-2 specified imagesas the upload directory (indicated by the $savefoldervariable). To make the folder writable by the web server, you can use your FTP client, or if you have command-line access, you can use the chmodcommand (chmod 777 /path/to/images).

To write the uploaded image to the target folder, you use the function move_uploaded_ file. This PHP function will retrieve the image and move it to the designated location. Additionally, it ensures that the file in question was in fact uploaded via the script. It returns a falsevalue if anything goes wrong, so it is important to use code to monitor that fact and react accordingly. If all goes well, voilà—you will have a brand-spanking new image uploaded to the folder of your choice, with almost no visible processing to the user. By making use of the onloadevent, you can then trigger a JavaScript function to pass the file name that has been uploaded to the parent frame (the one that initiated the upload). The onloadevent comes in handy for this because it lets you determine when the image has finished its upload to the server. The next section will show how to the display the uploaded image.