Explain Codes LogoExplain Codes Logo

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

javascript
fetch-api
file-upload
async-await
Alex KataevbyAlex Kataev·Oct 24, 2024
TLDR

To upload a file using the fetch API, here's a simple example:

const formData = new FormData(); // Note: Replace 'file' with your input's name attribute! formData.append('file', fileInput.files[0]); fetch('/upload', { method: 'POST', body: formData }) .then(res => res.json()) .then(data => console.log('Success:', data)) .catch(err => console.error('Panic:', err)); // Panic, but don't forget to breathe!

Have you prepared your server-side script to handle the incoming files?

Jazzing up with multiple files

Your app might need to upload multiple files. FormData is your best friend here:

const formData = new FormData(); for (let i = 0; i < fileInput.files.length; i++) { formData.append('files[]', fileInput.files[i]); // 'files[]' because we're uploading a band, not a solo act. } fetch('/multi-upload', { method: 'POST', body: formData }) // add your .then and .catch here

ProTip: By using FormData and not setting the Content-Type header, the browser ensures the correct boundary for you. Yup, it's that clever!

You wouldn't jump into the sea without a lifeguard. Similarly, wrapping your fetch with error handling is a must. Dip your toes into some async/await for cleaner code:

async function uploadFile(file) { const formData = new FormData(); formData.append('file', file); // The lifeguard to your surfboard. try { const response = await fetch('/upload', { method: 'POST', body: formData }); const data = await response.json(); console.log('Success:', data); } catch (err) { console.error('Cowabunga Error:', err); // Even surfers catch a wave wrong sometimes. } }

Trigger the function using the change event and you're good to go!

Peeking inside fetch() and unboxing Blob()

Content Type Control

Ever wanted control over your data format? The Content-Type header is your magic wand:

fetch('/upload-text', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: 'Up, Up, and Away!' // Your text is on its way! });

Fetching Blob Data

Sending a Blob? Upload it just like you would with any file:

const blob = new Blob(['Superman to Gotham'], { type: 'text/plain' }); // No Kryptonite, we promise. fetch('/upload-blob', { method: 'POST', body: blob });

Fetch treats Blob data just like a file.

Handling server-side responses

Every HTTP status code has a story to tell. Make sure to handle them well because after all, communication is key! Dissect data formats (like JSON, XML) like Sherlock would a crime scene.