Home >Web Front-end >JS Tutorial >How Can I Master File Uploads Using the JavaScript Fetch API?
Mastering File Upload with JS fetch API
Navigating the JS fetch API can be daunting, especially when tackling file uploads. Let's simplify this process by breaking it down step-by-step.
1. Capture the File Input
As demonstrated in your code, use a file input element to allow users to select files:
<form> <div> <label>Select file to upload</label> <input type="file"> </div> <button type="submit">Convert</button> </form>
2. Handle the Submit Event
Catch the submit event (replace the placeholder with your preferred event handler):
document.querySelector('form').addEventListener('submit', (event) => { // Prevent default form submission event.preventDefault(); // Retrieve the selected file const input = event.target.querySelector('input[type="file"]'); // Construct the request body const formData = new FormData(); formData.append('file', input.files[0]); // Submit the request fetch('/files', { method: 'POST', body: formData }).then(/* perform necessary actions */); });
3. Construct the Request Body
To send the file using fetch, use the FormData API. It creates a multipart/form-data request body. Append the selected file (input.files[0]) and any additional data, such as user information, to the formData object:
const formData = new FormData(); formData.append('file', input.files[0]); formData.append('user', 'username');
4. Initiate the fetch Request
With the request body ready, send the POST request using fetch, specifying the endpoint URL ('/files') and providing the formData object as the body:
fetch('/files', { method: 'POST', body: formData }) .then(/* handle the response as desired */);
And voila! You now have a fully functional file upload mechanism using the JS fetch API.
The above is the detailed content of How Can I Master File Uploads Using the JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!