File upload using the Fetch API
Wed Sep 07 2022 17:52:54 GMT+0000 (Coordinated Universal Time)
Saved by
@jimmywilliams
#javascript
const form = document.getElementById('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
const uploadElement = document.getElementById('file'); // Select file input element
const file = uploadElement.files[0]; // Selects file at position 0 (for single file)
const payload = new FormData(); // Sending in FormData object will set headers
payload.append('CV', file, 'CV.pdf'); // Appends file to FormData object
fetch('https://httpbin.org/post', { // Endpoint is a test API
method: "POST", // or "PUT"
body: payload,
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
});
content_copyCOPY
https://openjavascript.info/2022/06/08/how-to-upload-a-file-using-the-fetch-api/
Comments