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

php代码:

 1 <?php
 2 $fileName = $_FILES['afile']['name'];
 3 $fileType = $_FILES['afile']['type'];
 4 $fileContent = file_get_contents($_FILES['afile']['tmp_name']);
 5 $dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
 6 
 7 $json = json_encode(array(
 8   'name' => $fileName,
 9   'type' => $fileType,
10   'dataUrl' => $dataUrl,
11   'username' => $_REQUEST['username'],
12   'accountnum' => $_REQUEST['accountnum']
13 ));
14 
15 echo $json;
16 ?>

Html 及 JS 代码:

 1 <!DOCTYPE html>
 2 <!--
 3 Copyright 2012 Google Inc.
 4 
 5 Licensed under the Apache License, Version 2.0 (the "License");
 6 you may not use this file except in compliance with the License.
 7 You may obtain a copy of the License at
 8 
 9      http://www.apache.org/licenses/LICENSE-2.0
10 
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 
17 Author: Eric Bidelman (ericbidelman@chromium.org)
18 -->
19 <html>
20 <head>
21 <meta charset="utf-8" />
22 <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
23 <title>xhr.send(FormData) Example</title>
24 </head>
25 <body>
26  
27 <input type="file" name="afile" id="afile" accept="image/*"/>
28  
29 <script>
30 document.querySelector('#afile').addEventListener('change', function(e) {
31   var file = this.files[0];
32 
33   var fd = new FormData();
34   fd.append("afile", file);
35   // These extra params aren't necessary but show that you can include other data.
36   fd.append("username", "Groucho");
37   fd.append("accountnum", 123456);
38 
39   var xhr = new XMLHttpRequest();
40   xhr.open('POST', 'handle_file_upload.php', true);
41   
42   xhr.upload.onprogress = function(e) {
43     if (e.lengthComputable) {
44       var percentComplete = (e.loaded / e.total) * 100;
45       console.log(percentComplete + '% uploaded');
46     }
47   };
48 
49   xhr.onload = function() {
50     if (this.status == 200) {
51       var resp = JSON.parse(this.response);
52 
53       console.log('Server got:', resp);
54 
55       var image = document.createElement('img');
56       image.src = resp.dataUrl;
57       document.body.appendChild(image);
58     };
59   };
60 
61   xhr.send(fd);
62 }, false);
63 </script>
64 <!--[if IE]>
65 <script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
66 <script>CFInstall.check({mode: 'overlay'});</script>
67 <![endif]-->
68 </body>
69 </html>

备注:摘自《菜鸟教程》

posted @ 2022-03-30 10:15  muqiao  阅读(121)  评论(0编辑  收藏  举报