Uploading files in JavaScript can be done through the use of XMLHttpRequest (XHR), an object that allows you to send HTTP requests from a web client to a web server. To upload a file, you need to use XHR's send() method, which allows you to send the contents of the file to the server.
To upload, the first step is to create an XMLHttpRequest instance and set the onreadystatechange callback to handle the server response. Next, XHR's open() method should be used to specify the request method (for example, POST), the server URL, and whether the request should be made asynchronously.
Once the connection is established, the Content-Type header should be set to multipart/form-data, which indicates that the request contains binary data such as files. Finally, the send() method of XHR must be used, passing as a parameter the FormData object, which contains the file data.
In this way, the file is sent to the server and the upload is handled by the onreadystatechange callback. If the response from the server is positive, the file has been uploaded correctly and can be used by the server.
'use strict';
// Selects the input file from the HTML document
const fileInput = document.getElementById("file-input");
// Creates an XMLHttpRequest instance
const xhr = new XMLHttpRequest();
// We set up the callback to handle the server response
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// The file has been uploaded successfully
console.log("File successfully uploaded!");
}
};
// We open the connection to the server
xhr.open("POST", "/upload-file", true);
// We set the "Content-Type" header to "multipart/form-data"
xhr.setRequestHeader("Content-Type", "multipart/form-data");
// We create a FormData object and add the selected file
const formData = new FormData();
formData.append("file", fileInput.files[0]);
// We send the request to the server with the send() method
xhr.send(formData);
In conclusion, uploading files in JavaScript is a fairly simple operation and can be done using XMLHttpRequest and the FormData object. However, it is important to pay attention to the file size and error handling to ensure an optimal user experience.