Home  >  Article  >  Backend Development  >  Detailed explanation of the function of uploading files without refreshing in PHP_PHP tutorial

Detailed explanation of the function of uploading files without refreshing in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:40:281344browse

Some time ago, I made an ajax application, which involved an operation of uploading a file and then reading relevant content from the file. It is not difficult to upload files in PHP, but the difficulty is that the page must not be refreshed. After much deliberation, I have no idea. Later, I found a way to successfully upload files without refreshing in Baidu. I have sorted out my ideas and shared them with my friends. Criticisms and guidance are also welcome.
Tips: Use the target attribute of the form and iframe.
Friends who don’t like to read large sections of code can think about it for themselves. The completed test program is provided at the bottom of the article.

1. A php method for uploading files.
This method accepts a $file parameter, which is the $_FILES variable obtained from the client, and returns the renamed file name. If the upload fails, an empty string is returned.
php code

function uploadFile($file) {
// Upload path $destinationPath = "./upload/";
if (!file_exists($destinationPath)){
               mkdir($destinationPath, 0777); > If (Move_uploaded_file ($ file [tmp_name], $ DestinationPath. $ FILENAME) {Return iconv (GB2312, UTF-8, $ FILENAME);
} Return; >

2. Client-side HTML code

Here is the trick, add another iframe to achieve it. The form tag form defines an attribute target, which is explained as follows:
[pre]target attribute:
_blank ---------- New window _self ------ ----- Self_top ------------ Main frame
_parent --------- Parent frame
custom name ----- Appearing in the frame structure, the link will be opened in the frame of that name

In this example, the iframe name is used, so the link will be opened in the iframe when the form is submitted (that is, there is no refresh, to be precise it should be
No refresh feeling)
When the form is submitted, the startUpload method is called, of course this is defined by JS.
[/pre][pre]In addition, we also define a span to display prompt information. The code is as follows:
[/pre]xhtml code

Import file: