To download a binary file using JavaScript, you can utilize the Fetch API or XMLHttpRequest to retrieve the file and then use the Blob and URL.createObjectURL methods to create a downloadable link. Here's an example of how to do it:
Example 1: Using Fetch API
function downloadFile(url, filename) {
fetch(url)
.then(response => {
// Check if the response is okay
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob(); // Convert to blob
})
.then(blob => {
const url = window.URL.createObjectURL(blob); // Create a URL for the blob
const a = document.createElement('a'); // Create a link element
a.style.display = 'none';
a.href = url; // Set the href to the blob URL
a.download = filename; // Set the file name
document.body.appendChild(a); // Add the link to the document
a.click(); // Programmatically click the link
window.URL.revokeObjectURL(url); // Clean up
document.body.removeChild(a); // Remove the link from the document
})
.catch(error => console.error('There was a problem with the download:', error));
}
// Usage
downloadFile('https://example.com/path/to/your/file.bin', 'your-file.bin');
Example 2: Using XMLHttpRequest
function downloadFile(url, filename) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob'; // Set the response type to blob
xhr.onload = function () {
if (xhr.status === 200) {
const blob = xhr.response; // Get the blob response
const blobUrl = window.URL.createObjectURL(blob); // Create a blob URL
const a = document.createElement('a'); // Create a link element
a.style.display = 'none';
a.href = blobUrl;
a.download = filename; // Set the file name
document.body.appendChild(a); // Add the link to the document
a.click(); // Programmatically click the link
window.URL.revokeObjectURL(blobUrl); // Clean up
document.body.removeChild(a); // Remove the link from the document
} else {
console.error('Download failed:', xhr.statusText);
}
};
xhr.onerror = function () {
console.error('Network Error');
};
xhr.send(); // Send the request
}
// Usage
downloadFile('https://example.com/path/to/your/file.bin', 'your-file.bin');
Notes:
- Replace
'https://example.com/path/to/your/file.bin' with the actual URL of the binary file you want to download.
- Adjust the file name as necessary in the
filename parameter.
- Ensure that the server hosting the binary file allows cross-origin requests if you are fetching from a different domain (CORS policy).