Upload. php
Copy codeThe Code is 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 );
}
?>
Index.html
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> Html5 Ajax File Upload </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 = 200 | xhr. status = 0)
{
Var result = xhr. responseText;
Var json = eval ("(" + result + ")");
Alert ('image 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>
</Head>
<Body>
<Div class = "form-group">
<Label class = "control-label"> image </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 = "28" onchange = "document. getElementById ('textfield '). value = this. value "/>
<Span onclick = "UpladFile ()" class = "mybtn"> upload </span>
</Div>
</Body>
</Html>