Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upload a file with the JS fetch API?

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 */); 
like image 501
deitch Avatar asked Mar 17 '16 17:03

deitch


People also ask

How do I submit form data using Fetch?

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.


1 Answers

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 }) 
like image 53
Integ Avatar answered Oct 07 '22 22:10

Integ