Created
October 18, 2017 14:45
-
-
Save prof3ssorSt3v3/cbb06bf009a76abb581f7557ff747692 to your computer and use it in GitHub Desktop.
This file contains 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
//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