Skip to content

Instantly share code, notes, and snippets.

@kllaudyo
Last active August 6, 2018 18:12
Show Gist options
  • Save kllaudyo/ab330301363b61611df9e13bcf3fc962 to your computer and use it in GitHub Desktop.
Save kllaudyo/ab330301363b61611df9e13bcf3fc962 to your computer and use it in GitHub Desktop.
Realizar upload utilizando fetch
<html>
<body>
<input type="file" name="picture" id="picture" />
<pre></pre>
</body>
<script>
window.onload = function(){
const getRequestHeaders = () => new Headers({
'Accept': 'application/json'
});
const upload = data =>
//Imaginando um retorno do tipo: json_encode($_FILES);
fetch('/api', { method:'POST', headers:getRequestHeaders(), body:data })
.then( response => response.json())
.then( response => document.querySelector("pre").innerHTML = JSON.stringify(response))
.catch( error => document.querySelector("pre").innerHTML = JSON.stringify(error))
;
const multipart = arguments => {
//Ao utilizar FormData não utilizar o header Content-Type
const data = new FormData();
Object.keys(arguments).map(key => data.set(key, arguments[key]));
return data;
};
const onSelectFile = e => {
if(e.target.files)
upload(multipart({"file":e.target.files[0]}));
else
document.querySelector("pre").innerHTML = "Impossível anexar arquivo";
};
document.querySelector("#picture").onchange = onSelectFile
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment