I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form> <div> <label>Select file to upload</label> <input type="file"> </div> <button type="submit">Convert</button> </form>
And I can catch the submit
event using <fill in your event handler here>
. But once I do, how do I send the file using fetch
?
fetch('/files', { method: 'post', // what goes here? What is the "body" for this? content-type header? }).then(/* whatever */);
Add a form submit event listener First, select the form element and add an event listener to it, listening out for a submit event. And inside the function, apply the preventDefault() method to the event object to prevent the form being submitted by HTML by default.
I've done it like this:
var input = document.querySelector('input[type="file"]') var data = new FormData() data.append('file', input.files[0]) data.append('user', 'hubot') fetch('/avatars', { method: 'POST', body: data })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With