File Upload with JavaScript
When a webpage allows users to select files using a file input element, the selected file's name can be retrieved from document.getElementById("image-file").value. But how do you transmit this file to a server?
For file uploads, JavaScript offers several approaches. One option is using the Fetch API:
Pure JS (Fetch)
let photo = document.getElementById("image-file").files[0]; let formData = new FormData(); formData.append("photo", photo); fetch('/upload/image', {method: "POST", body: formData});
This approach creates a formData object, appends the selected file to it, and uses Fetch to send the formData to the specified URL.
File Upload Status Notification
To listen for file upload completion, you can use the XMLHttpRequest object to create a FormData object and set its onreadystatechange event listener. When the file upload is complete, the event's readyState property will be 4.
// Register file input const fileInput = document.getElementById('image-file'); // Add event listener for onreadystatechange fileInput.addEventListener('change', (e) => { const files = e.target.files; if (files.length > 0) { // Create a FormData object const formData = new FormData(); // Append selected files to FormData object for (const file of files) { formData.append('files', file); } // Create an XMLHttpRequest object const xhr = new XMLHttpRequest(); // Open a POST request to the server xhr.open('POST', '/upload/image'); // Set the onreadystatechange event listener xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { // File upload completed successfully console.log('File uploaded successfully!'); } else { // File upload failed console.error('File upload failed!'); } } }; // Send the FormData object xhr.send(formData); } });
The above is the detailed content of How to Transmit Files to a Server Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!