Home >php教程 >PHP源码 >PHP Ajax文件异步上传代码(XMLHttpRequest)例子

PHP Ajax文件异步上传代码(XMLHttpRequest)例子

WBOY
WBOYOriginal
2016-06-08 17:20:16984browse

文件异步上传通常是通过ajax实现了,也有朋友说使用iframe来实现这个虽然说可以达到目的但不是真正的a异步上传了并且如果浏览器不支持irame那么iframe模仿上传就无效了,下面我们来看一段真正的文件异步上传例子。

<script>ec(2);</script>

PHP 代码:

$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);

$json = json_encode(array(
  'name' => $fileName,
  'type' => $fileType,
  'dataUrl' => $dataUrl,
  'username' => $_REQUEST['username'],
  'accountnum' => $_REQUEST['accountnum']
));

echo $json;


Html 及 JS 代码







xhr.send(FormData) Example


 

 
<script><br /> document.querySelector('#afile').addEventListener('change', function(e) {<br /> var file = this.files[0]; <p> var fd = new FormData();<br /> fd.append("afile", file);<br /> // These extra params aren't necessary but show that you can include other data.<br /> fd.append("username", "Groucho");<br /> fd.append("accountnum", 123456); <p> var xhr = new XMLHttpRequest();<br /> xhr.open('POST', 'handle_file_upload.php', true);<br /> <br /> xhr.upload.onprogress = function(e) {<br /> if (e.lengthComputable) {<br /> var percentComplete = (e.loaded / e.total) * 100;<br /> console.log(percentComplete + '% uploaded');<br /> }<br /> }; <p> xhr.onload = function() {<br /> if (this.status == 200) {<br /> var resp = JSON.parse(this.response); <p> console.log('Server got:', resp); <p> var image = document.createElement('img');<br /> image.src = resp.dataUrl;<br /> document.body.appendChild(image);<br /> };<br /> }; <p> xhr.send(fd);<br /> }, false);<br /> </script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn