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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor
