Skip to content

Instantly share code, notes, and snippets.

@jcable
Created December 15, 2015 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcable/25d4c86d96d810a5498d to your computer and use it in GitHub Desktop.
Save jcable/25d4c86d96d810a5498d to your computer and use it in GitHub Desktop.
submit a form with a blob
<html>
<head>
<meta charset="UTF-8">
<script>
function init() {
var form = document.getElementById('f');
if(form) {
form.addEventListener('submit', function(event) {
if(form.ajax.checked) {
var formData = new FormData();
for(var i=0; i<form.length; i++) {
if(form[i].type == 'file') {
var files = form[i].files;
var blob = files[0].slice(0, files[0].size, files[0].type);
formData.append(form[i].name, blob, files[0].name);
}
else {
formData.append(form[i].name, form[i].value);
}
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
// what do I do here?
// is it
// window.location = URL.createObjectURL(xhr.response);
// or should it be
// document.write(responseText);
// or even
// document.close(); document.open(); document.write(xhr.responseText);
// or?
}
};
xhr.open('POST', form.action, true);
xhr.send(formData);
event.preventDefault();
}
}, false);
}
}
</script>
</head>
<body onload='init()'>
<?php
if(isset($_FILES['file'])) {
echo '<ul>';
echo '<li>name: '.$_FILES['file']['name'].'</li>';
echo '<li>type: '.$_FILES['file']['type'].'</li>';
echo '<li>size: '.$_FILES['file']['size'].'</li>';
echo '<li>upload type: '.$_POST['ajax'].'</li>';
echo '</ul>';
echo "<a href='http://localhost/test.php'>reset</a>";
}
else {
?>
<form enctype='multipart/form-data' id='f' method='POST'>
<input name='file' type='file'/>
ajax: <input name='ajax' type='checkbox'/>
<input type='submit'/>
</form>
<?php
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment