File Upload Using JavaScript FormData
Overview
The process of uploading files using JavaScript FormData involves three core steps:
| Step | Description |
|---|---|
| 1 | Instantiate a FormData object |
| 2 | Append files to the FormData instance |
| 3 | Transmit the FormData to the server |
Detailed Steps
1. Instantiating FormData
To begin, create a FormData object which will hold the data to be sent.
const uploadData = new FormData();
2. Appending Files to FormData
Next, retrieve the selected file from an input element and append it to the FormData object.
const fileSelector = document.querySelector('#fileInput');
uploadData.append('document', fileSelector.files[0]);
3. Sending FormData to Server
Finally, use either XMLHttpRequest or the Fetch API to send the FormData to the backend.
const request = new XMLHttpRequest();
request.open('POST', '/api/upload', true);
request.send(uploadData);
Relationship Diagram
A conceptual relationship can be illustrated as follows:
graph TD
A[File Input] --> B[FormData]
B --> C[Server Endpoint]
Flowchart
The workflow for uploading files with FormData can be visualized as:
- User selects a file via HTML input.
- JavaScript captures the file reference.
- File is appended to a FormData container.
- FormData is submitted via HTTP POST request.
- Server receives and processes the uploaded file.