PHP-based AJAX technology for asynchronous file Upload

Source: Internet
Author: User
PHP-based AJAX technology implements asynchronous file upload. I read the PHP-based AJAX technology to implement asynchronous file upload. asynchronous file upload is often encountered in modern AJAX-implemented Web applications, the problem that must be solved. However, the standard AJAX class (XmlHttpRequest) cannot implement the file transfer function. Therefore, the content discussed here is how to <LINKhref = "htt

Asynchronous file upload is a problem that must be solved frequently in modern AJAX-implemented Web applications. However, the standard AJAX class (XmlHttpRequest) cannot implement the file transfer function. Therefore, the content discussed here is how to build an asynchronous file upload function based on AJAX technology. In this function, you need to use the built-in box and (IFRAME) to transfer files. This function enables users to use this page and enter the file description when uploading files.

This example is based on the typical case of AJAX.

System environment

· Newer versions of browsers. For example, Opera, Firefox, or Internet Explorer.

· PHP 4.3.0 or later

· PHP Version 5

· Enable the 'short _ open_tag 'option in PHP (otherwise, a parsing error will occur ).

Function analysis

Upload files using the built-in IFRAME (framework. It consists of three parts.

· There is a simple <form... form in the middle of the page. The form only contains the <input type = "file"...> control. The target link of the form is a hidden IFRAME (implemented by the CSS style "display: none;"), and the OnChange event of the only control in the form is used to trigger JavaScript functions. This function is used to check the extension submitted by the user and then submit the form.

· On the server side, a processing process (using FILEFRAME to sit and comment) is written in PHP ). 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 changed the page that the user is viewing through "parent.w.w.doc ument", set the file name, and enable the button for the user to submit the form. The Enable button operation is implemented through the getElementById function.

· There is also a form on the home page that contains the description submitted by the user and the hidden file name. You can enter the description of the file while uploading the file. After the file is uploaded, click the button to view the file information returned to the user after the upload. (The file name returned and the description entered by the user constitute the file information ).

You may say that this operation does not conform to common sense: the file has been submitted before the user confirms. What if the user does not submit it. You can process the files abandoned by users by yourself.

In this example, the file is stored in the directory of a file system. You need to configure this directory when the script starts running. the specific variables that contain this directory information are $ upload_dir and $ web_upload_dir. Check whether the directory is writable.

Here we use the following PHP functions:

· Move_uploaded_file-transfers files uploaded to the server

· Fopen-open a file

· Fwrite-write content into a file

· Fclose-close the file

· Str_replace-replace string

· Filesize-returned file size

· Filemtime-return processing time

You can use the manual to find these functions. Note that you should replace the HTM (<,>, &) mark with (<,> and &).

Source code

<? Php
$ Upload_dir = "/var/www/anyexample/aeu"; // file storage path
$ Web_upload_dir = "/aeu"; // path of the file in 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 ['fileframework'])
{
$ Result = 'error ';
$ Result_msg = 'No FILE field found ';

If (isset ($ _ FILES ['file']) // receives the file from the browser
{
If ($ _ FILES ['file'] ['error'] = UPLOAD_ERR_ OK) // no error
{
$ Filename = $ _ FILES ['file'] ['name']; // file name
Move_uploaded_file ($ _ FILES ['file'] ['tmp _ name'], $ upload_dir. '/'. $ filename );
// Main process of processing-transfer the 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 '<script language = "JavaScript" type = "text/javascript">'. "\ n ";
Echo 'Var parDoc = callback parent.doc ument ;';
'
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 ("&", "&", $ s );
$ S = str_replace ("<", "<", $ 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
<Html> <Body>
<H1 >{$ filename} <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> Example by <a href = "http://www.anyexample.com/"> AnyExample </a>
</Body> END;
 
$ F = fopen ($ upload_dir. '/'.w.filename.'-desc.html', "w ");
Fwrite ($ f, $ html );
Fclose ($ f );
$ Msg = "File {$ filename} uploaded,
<A href = '{$ web_upload_dir}/your own filenameapps-desc.html'> see file information page </a> ";

$ F = fopen ($ upload_dir. "/upload-log.html", "");
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 -->
<Html> <Title> IFRAME Async file uploader example </title>
</Head>
<Body>
<? Php
If (isset ($ msg ))
Echo '<p style = "font-weight: bold;">'. $ msg. '</p> ';
?>
<H1> Upload file: <P> File will begin to upload just after selection. </p>
<P> You may write file description, while you 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 will send its post data to fileframe section of this PHP script (see 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 is called when user selects file in file dialog */
Function jsUpload (upload_field)
{
// This is just an example of checking file extensions
// If you do not 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 = "64" disabled>
<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. Other, hidden one is for sending data -->
<Input type = "hidden" name = "filename" id = "filename">
<Br>

<Label for = "photo"> File description: </label> <br>
<Textarea rows = "5" cols = "50" name = "description"> </textarea>

<Br>
<Input type = "submit" id = "upload_button" value = "save file" disabled>
</Form>
<Br>
<A href = "<? = $ Web_upload_dir?> /Upload-log.html "> upload-log </a>
<Br>

Example by <a href = "http://www.anyexample.com/"> AnyExample </a>
</Body>
</Html>

The above explanation provides an idea for your reference. You can also perform optimization based on your needs.

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.