PHP-based AJAX techniques for asynchronous file Upload

Source: Internet
Author: User
Asynchronous file upload is a title that is frequently encountered in modern AJAX Web application and must be resolved. 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 skills. In this function, asynchronous file upload is often encountered in the Web usage of modern AJAX implementation, and the title must be resolved. 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 skills. In this function, you need to apply the built-in box and (IFRAME) to transfer files. The consequence of this function is that when you upload a file to a page, you can also apply the page and enter the file description.

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 ).

Efficacy 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 this form is a hidden IFRAME (implemented by 'display: none; 'in CSS style), and the OnChange event of only one control in the form is used to trigger JavaScript functions. This function is used to check the extended name 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 keep them on the server. it is returned to the user through Javascript code. After returning the criptscript to the user, you can change the page that the user is viewing, set the file name, and enable the button for the user to submit the form. The Enable button 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 name of the hidden file. 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 Returned file name and user input description constitute the file information ).

It may be unreasonable to say that the file is submitted before the user confirms it. What would happen if the user did not submit it. You can expand the processing of files abandoned by users.

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 containing 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 the content into a file

· Fclose-closed file

· Str_replace-swap strings

· Filesize-returned file size



· Filemtime-return processing time

You can use the manual to find these functions as applications. Replace the HTM (<,>, &) tag 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 a file from a 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 _ click'). 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}/multiple objects filenameapps-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 -->
<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 = 'siden' name = 'fileframework' 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 = 'siden' 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 _ click' 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.