Skip to content

Instantly share code, notes, and snippets.

@tripolskypetr
Last active January 2, 2020 21:43
Show Gist options
  • Save tripolskypetr/05cf3429283224748f8776cb7e89228f to your computer and use it in GitHub Desktop.
Save tripolskypetr/05cf3429283224748f8776cb7e89228f to your computer and use it in GitHub Desktop.
JS serverless fetch and upload image https://jsfiddle.net/tripolskypetr/7sfp4vuy/
<body>
<script>
(async function() {
const fetchImage = async (url) => {
const data = await fetch(url);
const buffer = await data.arrayBuffer();
const blob = new Blob([buffer], { type: "image/png"});
return blob;
}
const sendImage = (blob, url = "http://foo.com/submitform.php", name = "image.png") => {
const request = new XMLHttpRequest();
const file = new File(blob, name)
const data = new FormData();
request.open("POST", url);
data.append("image", file, name);
request.send(data);
}
const showImage = (blob) => {
const image = document.createElement("img");
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
}
const url = "https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png";
const blob = await fetchImage(url);
showImage(blob);
// sendImage(blob);
})();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment