Last active
August 6, 2018 18:12
-
-
Save kllaudyo/ab330301363b61611df9e13bcf3fc962 to your computer and use it in GitHub Desktop.
Realizar upload utilizando fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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