Skip to content

Instantly share code, notes, and snippets.

@yookoala
Created September 26, 2018 08:20
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 yookoala/2de191252557f5a37de6878e72df2f14 to your computer and use it in GitHub Desktop.
Save yookoala/2de191252557f5a37de6878e72df2f14 to your computer and use it in GitHub Desktop.
FormData javascript API test
<?php
/**
* A very simple test of FormData API with a very simple
* PHP backend.
*
* Usage:
*
* 1. Save this file to a folder.
* 2. Open your terminal and cd to this folder.
* 3. Run `php -S localhost:8000 -t .`.
* 4. Open your browser and browse to `http://localhost:8000`.
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json');
try {
if (!empty($_FILES)) {
// aggregate upload results, if there are many.
$upload_results = array_map(function ($key) {
$file = &$_FILES[$key];
$file['path'] = __DIR__ . '/files/' . $file['name'];
$file['url'] = '/files/' . $file['name'];
if (!move_uploaded_file($file['tmp_name'], $file['path'])) {
throw new Exception('Error handling upload: ' .
json_encode(error_get_last()));
}
return $file;
}, array_keys($_FILES));
// show success response
echo json_encode([
'status' => 'success',
'method' => $_SERVER['REQUEST_METHOD'],
'content-type' => $_SERVER['CONTENT_TYPE'] ?: '',
'post' => $_POST,
'files' => $upload_results,
]);
} else {
throw new Exception('No file uploaded');
}
} catch (Exception $e) {
// show error response
echo json_encode([
'status' => 'error',
'error' => 'Error handling uploads',
'error_details' => $e->getMessages(),
'method' => $_SERVER['REQUEST_METHOD'],
'content-type' => $_SERVER['CONTENT_TYPE'] ?: '',
'post' => $_POST,
]);
}
exit;
}
?>
<!doctype html>
<html>
<head>
<title>FormData API test</title>
<style>
#myform {
display: block;
position: fixed;
width: 100%;
height: 2em;
}
#myresponse {
box-sizing: border-box;
width: 100%;
height: 100vh;
padding-top: 2.5em;
font-family: monospace;
}
</style>
</head>
<body>
<form id="myform">
<input type="file" id="myfile" />
</form>
<textarea id="myresponse"></textarea>
<script>
/**
* A simple JS test for form data API with PHP backend.
*/
(function () {
var file = document.getElementById('myfile');
var responseArea = document.getElementById('myresponse');
file.addEventListener('change', function () {
var formData = new FormData();
formData.append('myfile', this.files[0]);
// send form data with fetch
fetch('.', {
method: 'POST',
cache: 'no-cache',
body: formData,
}).then((response) => {
// create promise of text
return response.text();
}).then((text) => {
// put promise text to response area
console.log('response text', text);
responseArea.value = text;
});
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment