1const handleImageUpload = event => {
2 const files = event.target.files
3 const formData = new FormData()
4 formData.append('myFile', files[0])
5
6 fetch('/saveImage', {
7 method: 'POST',
8 body: formData
9 })
10 .then(response => response.json())
11 .then(data => {
12 console.log(data)
13 })
14 .catch(error => {
15 console.error(error)
16 })
17}
18
1// Select your input type file and store it in a variable
2const input = document.getElementById('fileinput');
3
4// This will upload the file after having read it
5const upload = (file) => {
6 fetch('http://www.example.net', { // Your POST endpoint
7 method: 'POST',
8 headers: {
9 // Content-Type may need to be completely **omitted**
10 // or you may need something
11 "Content-Type": "You will perhaps need to define a content-type here"
12 },
13 body: file // This is your file object
14 }).then(
15 response => response.json() // if the response is a JSON object
16 ).then(
17 success => console.log(success) // Handle the success response object
18 ).catch(
19 error => console.log(error) // Handle the error response object
20 );
21};
22
23// Event handler executed when a file is selected
24const onSelectFile = () => upload(input.files[0]);
25
26// Add a listener on your input
27// It will be triggered when a file will be selected
28input.addEventListener('change', onSelectFile, false);