How to upload a file using the JS fetch API?

I'm still trying to wrap my head around this.

I can suggest the user to select a file (or even several) by entering the file:

<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 as soon as I do this, how do I send a file using fetch ?

 fetch('/files', { method: 'post', // what goes here? What is the "body" for this? content-type header? }).then(/* whatever */); 
+139
javascript html5 fetch fetch-api
Mar 17 '16 at 17:31
source share
7 answers

This is a basic example with comments. The upload function is what you are looking for:

 // Select your input type file and store it in a variable const input = document.getElementById('fileinput'); // This will upload the file after having read it const upload = (file) => { fetch('http://www.example.net', { // Your POST endpoint method: 'POST', headers: { // Content-Type may need to be completely **omitted** // or you may need something "Content-Type": "You will perhaps need to define a content-type here" }, body: file // This is your file object }).then( response => response.json() // if the response is a JSON object ).then( success => console.log(success) // Handle the success response object ).catch( error => console.log(error) // Handle the error response object ); }; // Event handler executed when a file is selected const onSelectFile = () => upload(input.files[0]); // Add a listener on your input // It will be triggered when a file will be selected input.addEventListener('change', onSelectFile, false); 
+104
Mar 18 '16 at 10:31
source share

I did 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 }) 
+184
Nov 27 '16 at 8:05
source share

Important note for sending files using the Fetch API

You need to skip the content-type header for the Fetch request. Then the browser will automatically add a Content type header including the border of the form, which looks like

 Content-Type: multipart/form-data; boundary=β€”-WebKitFormBoundaryfgtsKTYLsT7PNUVD 

A form border is a separator for form data.

+63
Mar 27 '18 at 10:49
source share

If you want a multiple file, you can use this

 var input = document.querySelector('input[type="file"]') var data = new FormData() for (const file of input.files) { data.append('files',file,file.name) } fetch('/avatars', { method: 'POST', body: data }) 
+27
May 22 '18 at 16:56
source share

To send a single file, you can simply use the File object from the input the .files array directly as the value of body: in the fetch() initializer:

 const myInput = document.getElementById('my-input'); // Later, perhaps in a form 'submit' handler or the input 'change' handler: fetch('https://example.com/some_endpoint', { method: 'POST', body: myInput.files[0], }); 

This works because File inherits from Blob and Blob is one of the valid BodyInit types defined in the Fetch standard.

+16
Jan 23 '18 at 19:52
source share

Jumps from Alex Montoya's approach for multiple file entry elements

 const inputFiles = document.querySelectorAll('input[type="file"]'); const formData = new FormData(); for (const file of inputFiles) { formData.append(file.name, file.files[0]); } fetch(url, { method: 'POST', body: formData }) 
+1
Oct 25 '18 at 19:44
source share

The problem for me was that I used response.blob () to populate the form data. Apparently, you cannot do this, at least with responsive native, so I ended up using

 data.append('fileData', { uri : pickerResponse.uri, type: pickerResponse.type, name: pickerResponse.fileName }); 

Fetch seems to recognize this format and sends the file where the URI points to.

+1
Nov 03 '18 at 3:03
source share



All Articles