Home > Backend Development > PHP Tutorial > Example of image file upload function using php+ajax_PHP tutorial

Example of image file upload function using php+ajax_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 10:24:42
Original
770 people have browsed it

There are several commonly used asynchronous file upload functions at present. The more common ones are the use of iframe framework form, ajax function effect, and flash+php function. Here are examples of asynchronous file upload functions implemented by ajax and iframe.

Method 1, use jquery ajaxfileupload.js to upload files

In fact, it is to achieve refresh-free file upload. The IFRAME file upload principle can be used.
Actually when uploading files with PHP. . . Only the $_FILES format can be used, but if we just use JS to get its ID, such as ..document.getElementById('img').value or jquery $("#img") in the form cannot be actually uploaded (but there are still many people doing this, including me at the beginning).
But the function also requires the implementation of the so-called "asynchronous upload", what should I do? You can only use third-party components, or write one yourself (embed an IFRAME in the web page). But if you are considering development time, it is recommended to use a third party. Here is a good jQuery Ajax file upload component, namely "ajaxfileupload.js". Its component download address is: http://files.jb51.net/file_images /article/201306/js/ajaxfileupload.js

Process:

(1) Front-end file code: test.php

Copy code The code is as follows:

The corresponding HTML is:


The client is now complete.

(2) doajaxfileupload.php on the server side

In order to easily detect whether the value is actually passed here, you can save it.

Copy code The code is as follows:
$file_infor = var_export($_FILES,true);
file_put_contents("d:file_infor. php".$file_infor);

In this way, when you call the file_infor.php file you just generated, you will see the familiar information again:

Copy code The code is as follows:
array(
'name'=>'lamp.jpg',
' type'=>'image/pjpeg',
'tmp_name'=>'c:windowstempphpFA.tmp',
'error'=>0,
'size'=>3127
)

Of course, the real processing is similar to this:

Copy code The code is as follows:
$upFilePath = "d:/";
$ok =@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);
if($ok === FALSE){
echo json_encode('file_infor'=>'Upload failed' );
}else{
echo json_encode('file_infor'=>'Upload successful');
}
?>

Method 2, use iframe to upload images

The html code is as follows:

Copy code The code is as follows: