upload file with fetch code example
Example 1: uploading file with fetch
const input = document.getElementById('fileinput');
const upload = (file) => {
fetch('http://www.example.net', {
method: 'POST',
headers: {
"Content-Type": "You will perhaps need to define a content-type here"
},
body: file
}).then(
response => response.json()
).then(
success => console.log(success)
).catch(
error => console.log(error)
);
};
const onSelectFile = () => upload(input.files[0]);
input.addEventListener('change', onSelectFile, false);
Example 2: fetch file upload
const handleImageUpload = event => {
const files = event.target.files
const formData = new FormData()
formData.append('myFile', files[0])
fetch('/saveImage', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.error(error)
})
}