PHP Ajax Technology Implementation of file asynchronous upload

Source: Internet
Author: User
Tags parse error php script save file setcookie

Asynchronous file uploads are frequently encountered and must be addressed in modern AJAX-enabled Web applications. But the standard Ajax class (XMLHttpRequest) does not implement the ability to transfer files. So what we're talking about here is how to build asynchronous file uploads on the basis of Ajax technology. In this function, you need to use the built-in boxes and (IFRAME) to transfer files. The effect of this function is that when the page uploads the file, the user can also use the page and fill in the file description.

This example is an analysis of the classic examples of Ajax that we cite.

System environment

· Newer version of the browser. such as Opera,firefox or Internet Explorer.

· PHP 4.3.0 or later

· PHP 5 version

· The ' short_open_tag ' option in PHP is turned on (otherwise a parse error will occur).

Functional analysis

Files are uploaded through the built-in iframe (frame). Consists of three parts.

· In the middle of the page there is a simple <form ... form, the form contains the <input type= "file" ... > control. This form's target link is a hidden iframe (through the CSS style "display:none;" Implementation) and the onchange event for the only control within the form to trigger the JavaScript function. The function is to check the extension that the user submits, and then submit the form.

· A processing process was written on the server side using PHP (Fileframe sat annotated). This process is used to check the files uploaded from the client and save them on the server and return them to the user in the form of JavaScript code. The JavaScript script returned to the user changes the page that the user is currently viewing through "parent.window.document", sets the name of the file, and enables the button for the user to submit the form. The action to enable the button is implemented through the getElementById function.

· There is also a form on the main page that contains the user-submitted description and the hidden file name. The user can fill in the description of the file while uploading the file. When the file is uploaded, the user clicks on the button and can see the file information returned to the user after uploading. (form file information by returning a filename and a description of the user input).

You might say it's not common sense to do this: The file has been submitted before the user confirms it. What would happen if the user did not submit it? You can handle files that are discarded by the user at the extension.

This example stores the file in a directory on a file system. You need to configure this directory when the script starts to run, and the specific variables that contain this directory information are $upload_dir and $web_upload_dir. Here is a permission check for whether the directory is writable.

Here we use the following PHP functions:

· Move_uploaded_file-Transfer once uploaded to server file

· fopen-Open File

· Fwrite-writing content to a file

· Fclose-Close File

· Str_replace-Replacement string

· FileSize-Returns the file size

· Filemtime-Return processing time

You can find these functions in the manual if used. Note that you want to replace the HTM (&) tags with (&lt;, &gt; and &amp;).


Source



<?php
$upload _dir = "/var/www/anyexample/aeu"; Path to file storage
$web _upload_dir = "/aeu"; The path of the file under the Web directory
$TF = $upload _dir. '/' MD5 (rand ()). ". Test ";
$f = @fopen ($TF, "w");
if ($f = = False)
Die ("Fatal error! {$upload _dir} is not writable. Set ' chmod 777 {$upload _dir} '
Or something like this ");
Fclose ($f);
Unlink ($TF);

Process uploaded files
if (Isset ($_post[' fileframe '))
{
$result = ' ERROR ';
$result _msg = ' No FILE field found ';

if (isset ($_files[' file '))//Accept file from browser
{
if ($_files[' file '] [' error '] = = UPLOAD_ERR_OK)//No Error
{
$filename = $_files[' file ' [' Name ']; Filename
Move_uploaded_file ($_files[' file '] [' tmp_name '], $upload _dir. '/'. $filename);
Main process of processing-transfer files to $upload _dir
$result = ' OK ';
}
ElseIf ($_files[' file '] [' error '] = = upload_err_ini_size)
$result _msg = ' The uploaded file exceeds the upload_max_filesize directive in php.ini ';
Else
$result _msg = ' Unknown error ';
}

Echo ' Echo ' <script language= "JavaScript" type= "Text/javascript" "." \ n ";
Echo ' var pardoc = window.parent.document; ';
'
if ($result = = ' OK ')
{
Echo ' Pardoc.getelementbyid ("Upload_status"). Value = "file successfully uploaded";
Echo ' Pardoc.getelementbyid ("filename"). Value = "'. $filename. ';
Echo ' Pardoc.getelementbyid ("Filenamei"). Value = "'. $filename. '; ';
Echo ' Pardoc.getelementbyid ("Upload_button"). Disabled = false; ';
}
Else
{
Echo ' Pardoc.getelementbyid ("Upload_status"). Value = "ERROR: '. $result _msg. '";
}

echo "\ n". ' </script> </body> Exit ();
}

function safehtml ($s)
{
$s =str_replace ("&", "&amp;", $s);
$s =str_replace ("a", "&lt;", $s);
$s =str_replace (">", "&gt;", $s);
$s =str_replace ("'", "&apos;", $s);
$s =str_replace ("\" "," &quot; ", $s);
return $s;
}

if (isset ($_post[' description '))
{
$filename = $_post[' filename '];
$size = FileSize ($upload _dir. '/'. $filename);
$date = Date (' R ', Filemtime ($upload _dir. '/'. $filename));
$description = safehtml ($_post[' description '));

$html =<<<end
<body>
<p> This is a file information page for your uploaded file. Bookmark it, or send to anyone ... </p>
<p> Date: {$date} </p>
<p> Size: {$size} bytes </p>
<p> Description:
<pre> {$description} </pre>
</p>
<p> <a Href= "{$web _upload_dir}/{$filename}" style= "Font-size:large;" >download file </a> <br>
<a Href= "{$PHP _self}" style= "Font-size:small;" >back to file uploading </a> <br>
<a Href= "{$web _upload_dir}/upload-log.html" style= "Font-size:small;" >upload-log </a> </p>
<br> <br> Example by <a Href= "http://www.anyexample.com/" >anyexample </a>
</body> End;
 
$f = fopen ($upload _dir. '/'. $filename. '-desc.html ', ' W ');
Fwrite ($f, $html);
Fclose ($f);
$msg = "File {$filename} uploaded,
<a Href= ' {$web _upload_dir}/{$filename}-desc.html ' >see file Information page </a> ';

$f = fopen ($upload _dir.) /upload-log.html "," a ");
Fwrite ($f, "<p> $msg </p> \ n");
Fclose ($f);

Setcookie (' msg ', $msg);
Header ("location:http://". $_server[' Http_host '). $PHP _self);
Exit ();
}

if (Isset ($_cookie[' msg ')) && $_cookie[' msg ']!= ')
{
if (GET_MAGIC_QUOTES_GPC ())
$msg = stripslashes ($_cookie[' msg ']);
Else
$msg = $_cookie[' msg '];
Setcookie (' msg ', ');
}
? >
!--beginning of Main Page-->
<title> IFRAME Async File Uploader Example </title>
<body>
<?php
if (Isset ($msg))
Echo ' <p style= ' font-weight:bold; > $msg. ' </p> ';
? >
<p> File would begin to upload just after selection. </p>
<p> You could write file description, while your file is being uploaded. </p>

<form action= "<?= $PHP _self?>" target= "Upload_iframe" method= "post" enctype= "Multipart/form-data"
<input type= "hidden" name= "Fileframe" value= "true"
!--Target of the form is set to hidden IFrame-->
!--from would send its post data to Fileframe section of this PHP script (above)-->

<label for= "file" >text file uploader: </label> <br>
!--JavaScript is called by OnChange attribute-->
<input type= "File" name= "file" id= "file" onchange= "Jsupload (This)" "
</form>
<script type= "Text/javascript"
/* This function was called when user selects file in file Dialog * *
function Jsupload (Upload_field)
{
This is just a example of checking file extensions
If you don't need extension checking, remove
Everything down to Line
Upload_field.form.submit ();
 
var re_text =/\.txt|\.xml|\.zip/i;
var filename = upload_field.value;

/* Checking File type * *
if (Filename.search (re_text) = =-1)
{
Alert ("File does not have text (TXT, XML, Zip) extension");
Upload_field.form.reset ();
return false;
}

Upload_field.form.submit ();
document.getElementById (' Upload_status '). Value = "Uploading file ...";
Upload_field.disabled = true;
return true;
}
</script>
<iframe name= "Upload_iframe" style= "width:400px; height:100px; Display:none; " >
</iframe>
!--for debugging purposes, it's often useful to remove
"Display:none" from style= "" Attribute-->

<br>
Upload Status: <br>
<input type= "text" name= "Upload_status" id= "Upload_status"
Value= "not uploaded" Size= "disabled>"
<br> <br>

File Name: <br>
<input type= "text" name= "Filenamei" id= "Filenamei" value= "None" disabled>

<form action= "<?= $PHP _self?>" method= "POST"
!--one field is ' disabled ' for displaying-only. Hidden one for sending data-->
<input type= "hidden" name= "filename" id= "filename" >
<br> <br>

<label for= "Photo" >file Description: </label> <br>
<textarea rows= "5" cols= "a" name= "description" > </textarea>

<br> <br>
<input type= "Submit" id= "Upload_button" value= "Save File" disabled>
</form>
<br> <br>
<a Href= "<?= $web _upload_dir?>/upload-log.html" >upload-log </a>
<br> <br> <br>

Example by <a Href= "http://www.anyexample.com/" >anyexample </a>
</body>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.