ArticleZip > How Do I Upload A File With The Js Fetch Api

How Do I Upload A File With The Js Fetch Api

Uploading files using the JS Fetch API is a common task for web developers looking to add robust file handling capabilities to their applications. In this guide, we will walk you through the process step by step, making it easy for you to enhance your web projects with file upload functionality.

To begin, let's create a simple HTML form that allows users to select a file for uploading:

Html

<button type="submit">Upload File</button>

In this form, we have an input element of type "file" where users can choose the file they want to upload. The form also contains a submit button that will trigger the upload process.

Next, let's write the JavaScript code that handles the file upload using the Fetch API:

Js

document.getElementById('fileUploadForm').addEventListener('submit', async (event) =&gt; {
    event.preventDefault();
    
    const fileInput = document.getElementById('fileInput');
    
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('https://api.example.com/upload', {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            console.log('File uploaded successfully');
        } else {
            console.error('Upload failed');
        }
    } catch (error) {
        console.error('An error occurred:', error);
    }
});

In the JavaScript code above, we first prevent the default form submission behavior to handle the upload process programmatically. We then get the file selected by the user and create a FormData object to hold the file data. The FormData object is constructed using the append method, where we specify the key 'file' and the file itself.

Using the Fetch API, we make a POST request to the specified URL ('https://api.example.com/upload') with the file data in the request body. If the response is successful (status code 200-299), we log a success message; otherwise, we log an error message.

Remember to replace 'https://api.example.com/upload' with the actual endpoint where you want to upload the file in your application.

And there you have it! With this code snippet, you can easily implement file uploads using the Fetch API in your web projects. Feel free to customize and expand upon this example to suit your specific requirements and make your file upload feature even more robust.

×