DeveloperBreeze

JavaScript File Upload using Fetch API and FormData

javascript
// Get the file input element
const fileInput = document.querySelector('#file-input');

// Add an event listener for the 'change' event on the file input
fileInput.addEventListener('change', (event) => {
    // Get the selected file
    const file = event.target.files[0];

    // Create a FormData object and append the file to it
    const formData = new FormData();
    formData.append('file', file);

    // Use the Fetch API to send a POST request with the file data
    fetch('/upload', { method: 'POST', body: formData });
});

Related Posts

More content you might like

Tutorial
javascript

JavaScript in Modern Web Development

  • Frameworks like Electron allow creating cross-platform desktop apps.
  • Example: Visual Studio Code.
  • JavaScript is used in IoT devices for controlling hardware and sensors.
  • Example: Node.js-based IoT applications.

Dec 10, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

AJAX allows form submissions to be processed in the background without reloading the page.

Fetch and display search results in real-time as users type in the search box.

Sep 18, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path

function UserList() {
    const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;
  • Reusability: The useFetch hook can be used across different components and applications, reducing code duplication and simplifying API interaction.
  • Loading and Error States: Automatically manages loading and error states, providing a consistent way to handle asynchronous operations.
  • Cleanup Handling: Prevents state updates on unmounted components, reducing potential memory leaks and ensuring stability.

Aug 12, 2024
Read More
Code
javascript json

JavaScript Code Snippet: Fetch and Display Data from an API

No preview available for this content.

Aug 04, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!