Чтобы получить массив байтов из файла в JavaScript, вы можете использовать различные методы. Вот несколько распространенных подходов:
-
Использование Fetch API:
fetch('file.txt') .then(response => response.arrayBuffer()) .then(buffer => { const byteArray = new Uint8Array(buffer); // Use the byte array as needed }) .catch(error => { // Handle any errors }); -
Использование XMLHttpRequest:
const xhr = new XMLHttpRequest(); xhr.open('GET', 'file.txt', true); xhr.responseType = 'arraybuffer'; xhr.onload = function () { if (xhr.status === 200) { const byteArray = new Uint8Array(xhr.response); // Use the byte array as needed } }; xhr.send(); -
Использование FileReader API:
const fileInput = document.getElementById('file-input'); const file = fileInput.files[0]; const reader = new FileReader(); reader.onloadend = function () { const arrayBuffer = reader.result; const byteArray = new Uint8Array(arrayBuffer); // Use the byte array as needed }; reader.readAsArrayBuffer(file);
Эти методы позволяют вам читать содержимое файла как массив байтов в JavaScript. Не забудьте адаптировать код в соответствии с вашими конкретными требованиями, такими как имя файла или обработка ввода.