Php+ajax realization picture File Upload function Instance _php skill

Source: Internet
Author: User
Tags function examples rand

There are several commonly used asynchronous file upload functions, such as the use of the IFRAME frame form, Ajax function effect, as well as the flash+php function, the following describes the Ajax and iframe asynchronous file upload function examples.

Method one, using jquery ajaxfileupload.js to implement file upload

In fact, the implementation of no refresh file upload. Can be used in the IFrame file upload principle.
In fact, when uploading files in PHP ... Can only use $_files form, but if we are only a single JS way to take its ID, such as <input id= ' img ' type= ' file '. document.getElementById (' img '). Value or jquery $ ("#img") are not actually transmitted (but there are a lot of people doing it, and I was at first).
But the function is also required to achieve the so-called "asynchronous upload", How to do? You can only use a third party component, or write one yourself (embed an IFRAME in a Web page). But if the development time is considered, it is recommended to use a third party, here is a good jquery Ajax file Upload component, namely "Ajaxfileupload.js", its component download address: http://files.jb51.net/file_images/ Article/201306/js/ajaxfileupload.js

Process:

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

Copy Code code as follows:
<script type= "Text/javascript" src= "Jquery.js" ></script>
<script type= "Text/javascript" src= "Ajaxfileupload.js" ></script>
<script type= "Text/javascript" >
function Ajaxfileupload ()
{
$.ajaxfileupload
(
{
URL: ' doajaxfileupload.php ',//You process the service side of the uploaded file
Secureuri:false,
Fileelementid: ' img ',
DataType: ' JSON ',
Success:function (data)
{
alert (data.file_infor);
}
}
)
return false;
}
</script>

The corresponding HTML is:

<input id= "img" type= "file" size= "name=" "img" class= "Input" >
<button class= "button" id= "Buttonupload" onclick= "return Ajaxfileupload ();" >Upload</button>

So the client is done.

(2) on the server side of the doajaxfileupload.php

Here you can save it for a simple test to see if the actual pass value comes in.

Copy Code code as follows:
$file _infor = Var_export ($_files,true);
File_put_contents ("d:file_infor.php". $file _infor);

So you call the file_infor.php file you just generated, and you see the familiar information:

Copy Code code as follows:
Array
' Name ' => ' lamp.jpg ',
' Type ' => ' image/pjpeg ',
' Tmp_name ' => ' c:windowstempphpfa.tmp ',
' Error ' =>0,
' Size ' =>3127
)

Of course, the real deal class is like this:

Copy Code code as follows:
<?php
$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 ' => ' uploaded success ');
}
?>

Method two, using the IFRAME frame to upload pictures

The HTML code is as follows:

Copy Code code as follows:
<div class= "frm" >
<form name= "Uploadfrom" id= "Uploadfrom" action= "upload.php" "method=" Post "target=" Tarframe "enctype=" multipart/ Form-data ">
<input type= "File" id= "Upload_file" name= "Upfile" >
</form>
<iframe src= "" "width=" 0 "height=" 0 "style=" display:none; "Name=" Tarframe "></iframe>
</div>
<div id= "MSG" >
</div>

Index.js file:

Copy Code code as follows:
$ (function () {
$ ("#upload_file"). Change (function () {
$ ("#uploadFrom"). Submit ();
});
});
function Stopsend (str) {
var im= "$ ("#msg"). append (IM);
}


upload.php file:

Copy Code code as follows:
<?php
$file =$_files[' upfile '];
$name =rand (0,500000). Dechex (rand (0,10000)). ". JPG ";
Move_uploaded_file ($file [' Tmp_name '], "upload/images/". $name);
Call the JS function of the IFRAME parent window
echo "<script>parent.stopsend (' $name ') </script>";
?>

Method III, original eco-ajax file Upload

Copy Code code as follows:

<! DOCTYPE html>
&LT;TITLE&GT;HTML5 Ajax upload file </title>
<meta charset= "Utf-8" >
<script type= "Text/javascript" >
var xhr;
function Createxmlhttprequest ()
{
if (window. ActiveXObject)
{
XHR = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest)
{
XHR = new XMLHttpRequest ();
}
}
function Upladfile ()
{
var fileobj = document.getElementById ("file"). Files[0];
var filecontroller = ' upload.php ';
var form = new FormData ();
Form.append ("MyFile", fileobj);
Createxmlhttprequest ();
Xhr.onreadystatechange = Handlestatechange;
Xhr.open ("Post", Filecontroller, True);
Xhr.send (form);
}
function Handlestatechange ()
{
if (xhr.readystate = 4)
{
if (xhr.status = = | | xhr.status = 0)
{
var result = Xhr.responsetext;
var json = eval ("+ result +"));
Alert (' Picture link: n ' +json.file);
}
}
}
</script>
<style>
. txt{height:28px; border:1px solid #cdcdcd; width:670px;
. mybtn{Background-color: #FFF; line-height:14px;vertical-align:middle;border:1px solid #CDCDCD; height:30px; width : 70px;}
. file{Position:absolute; top:0; right:80px; height:24px; Filter:alpha (opacity:0); opacity:0;width:260px}
</style>
<body>
<div class= "Form-group" >
<label class= "Control-label" > Pictures </label>
<br/>
<input type= ' text ' name= ' TextField ' id= ' textfield ' class= ' txt '/>
<span onclick= "File.Click ()" class= "mybtn" > Browse ...</span>
<input type= "File" name= "file" class= "file" id= "file" size= "" onchange= "document.getElementById (' TextField '). Value=this.value "/>
<span onclick= "Upladfile ()" class= "mybtn" > Upload </span>
</div>
</body>

PHP Code:

Copy Code code as follows:

<?php
if (Isset ($_files["myfile"]))
{
$ret = Array ();
$uploadDir = ' images '. Directory_separator.date ("Ymd"). Directory_separator;
$dir = DirName (__file__). Directory_separator. $uploadDir;
File_exists ($dir) | | (MkDir ($dir, 0777,true) && chmod ($dir, 0777));
if (!is_array ($_files["myfile" ["Name"])//single file
{
$fileName = Time (). Uniqid (). PathInfo ($_files["myfile"] ["name"]) [' extension '];
Move_uploaded_file ($_files["myfile"] ["Tmp_name"], $dir. $fileName);
$ret [' file '] = Directory_separator. $uploadDir. $fileName;
}
echo Json_encode ($ret);
}
?>

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.