public
Last active

Uploading files using xhr.send(FormData) to PHP server

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

Thanks so much :)
I was looking for how to use $_FILES with an AJAX post and everywhere they only showed the JavaScript but not how to handle the data in PHP.

Does this work in IE? I havin gissues in IE getting things to work properly with the fd FormData.

hy
"var resp = JSON.parse(this.response);"
whats wrong with this above line in IE ?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.