Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created October 18, 2017 14:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/cbb06bf009a76abb581f7557ff747692 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/cbb06bf009a76abb581f7557ff747692 to your computer and use it in GitHub Desktop.
//fetch using a Request and a Headers objects
// uploading an image along with other POST data
//using jsonplaceholder for the data
const url = 'https://postman-echo.com/post';
document.addEventListener('DOMContentLoaded', init);
function init(){
document.getElementById('btnSubmit').addEventListener('click', upload);
}
function upload(ev){
ev.preventDefault(); //stop the form submitting
//create any headers we want
let h = new Headers();
h.append('Accept', 'application/json'); //what we expect back
//bundle the files and data we want to send to the server
let fd = new FormData();
fd.append('user-id', document.getElementById('user_id').value);
let myFile = document.getElementById('avatar_img').files[0];
fd.append('avatar', myFile, "avatar.png");
// $_FILES['avatar']['file_name'] "avatar.png"
let req = new Request(url, {
method: 'POST',
headers: h,
mode: 'no-cors',
body: fd
});
fetch(req)
.then( (response)=>{
document.getElementById('output').textContent = "Response received from server";
})
.catch( (err) =>{
console.log('ERROR:', err.message);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment