Advertisement
HabelFoc

Javascript - using fetch api

Jun 9th, 2018
1,822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const file = document.querySelector('#file')
  2.  
  3. function upload(file){
  4.     fetch('https://www.example.com', { // // Your POST endpoint
  5.         method: 'POST',
  6.         headers: {
  7.             "Content-Type": "image/png" //  specify your content type (json or text or imge - look at google how to specify your content according to your data type)
  8.         },
  9.         body: file // your file object to be passed
  10.     })
  11.     .then(response => console.log(response.json)) // if the response is json object
  12.     .then(success => console.log(success)) // return success response if request is sucessfull
  13.     .catch(error => console.log('An error occurred: ', error)) // listen for error occurring...
  14. }
  15.  
  16. const startUpload = () => upload(file.files[0]);
  17.  
  18. file.addEventListener('change', startUpload, true);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement