Implementation of file asynchronous uploading based on PHP Ajax technology

Source: Internet
Author: User
Tags date exit contains file size file system functions parse error php script
Ajax| Upload | asynchronous

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

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 the HTM (,,, &) tags are replaced with (., > and &).
Source

$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);  
//Process main process-transfer file 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 '

echo "\ n". ' ';
Exit ();
}

function safehtml ($s)
{
$s =str_replace ("&", "&", $s);
$s =str_replace ("a", "<", $s);
$s =str_replace (">", ">", $s);
$s =str_replace ("'", "'", $s);
$s =str_replace ("\" "," "", $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, "

$msg

\ 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-->

IFRAME Async File Uploader Example


if (Isset ($msg))
Echo '

';
? >

Upload File:


File would begin to upload just after selection.


You could write file description, while your file is being uploaded.

!--Target of the form is set to hidden IFrame-->
!--from would send its post data to Fileframe section of this PHP script (above)-->

text file uploader:

!--JavaScript is called by OnChange attribute-->

/* 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;
}

&lt;br&gt;
!--for debugging purposes, it's often useful to remove
"Display:none" from style= "" Attribute-->



Upload Status:

Value= "not uploaded" Size= "disabled>"


File Name:

!--one field is ' disabled ' for displaying-only. Hidden one for sending data-->



file Description:









upload-log



Example by anyexample

The above explanation is to provide a kind of train of thought for everybody reference. We can also according to their own needs for the corresponding optimization.



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.