Javascript get input file data

File и FileReader

Объект File наследуется от объекта Blob и обладает возможностями по взаимодействию с файловой системой.

Есть два способа его получить.

Во-первых, есть конструктор, похожий на Blob :

new File(fileParts, fileName, [options])
  • fileParts – массив значений Blob / BufferSource /строки.
  • fileName – имя файла, строка.
  • options – необязательный объект со свойством:
    • lastModified – дата последнего изменения в формате таймстамп (целое число).

    Во-вторых, чаще всего мы получаем файл из или через перетаскивание с помощью мыши, или из других интерфейсов браузера. В этом случае файл получает эту информацию из ОС.

    Так как File наследует от Blob , у объектов File есть те же свойства плюс:

    В этом примере мы получаем объект File из :

       

    Через можно выбрать несколько файлов, поэтому input.files – псевдомассив выбранных файлов. Здесь у нас только один файл, поэтому мы просто берём input.files[0] .

    FileReader

    FileReader объект, цель которого читать данные из Blob (и, следовательно, из File тоже).

    Данные передаются при помощи событий, так как чтение с диска может занять время.

    let reader = new FileReader(); // без аргументов
    • readAsArrayBuffer(blob) – считать данные как ArrayBuffer
    • readAsText(blob, [encoding]) – считать данные как строку (кодировка по умолчанию: utf-8 )
    • readAsDataURL(blob) – считать данные как base64-кодированный URL.
    • abort() – отменить операцию.

    Выбор метода для чтения зависит от того, какой формат мы предпочитаем, как мы хотим далее использовать данные.

    • readAsArrayBuffer – для бинарных файлов, для низкоуровневой побайтовой работы с бинарными данными. Для высокоуровневых операций у File есть свои методы, унаследованные от Blob , например, slice , мы можем вызвать их напрямую.
    • readAsText – для текстовых файлов, когда мы хотим получить строку.
    • readAsDataURL – когда мы хотим использовать данные в src для img или другого тега. Есть альтернатива – можно не читать файл, а вызвать URL.createObjectURL(file) , детали в главе Blob.

    В процессе чтения происходят следующие события:

    • loadstart – чтение начато.
    • progress – срабатывает во время чтения данных.
    • load – нет ошибок, чтение окончено.
    • abort – вызван abort() .
    • error – произошла ошибка.
    • loadend – чтение завершено (успешно или нет).

    Когда чтение закончено, мы сможем получить доступ к его результату следующим образом:

    Наиболее часто используемые события – это, конечно же, load и error .

       

    Как упоминалось в главе Blob, FileReader работает для любых объектов Blob, а не только для файлов.

    Поэтому мы можем использовать его для преобразования Blob в другой формат:

    • readAsArrayBuffer(blob) – в ArrayBuffer ,
    • readAsText(blob, [encoding]) – в строку (альтернатива TextDecoder ),
    • readAsDataURL(blob) – в формат base64-кодированного URL.

    Для веб-воркеров доступен синхронный вариант FileReader , именуемый FileReaderSync.

    Его методы считывания read* не генерируют события, а возвращают результат, как это делают обычные функции.

    Но это только внутри веб-воркера, поскольку задержки в синхронных вызовах, которые возможны при чтении из файла, в веб-воркерах менее важны. Они не влияют на страницу.

    Итого

    File объекты наследуют от Blob .

    Помимо методов и свойств Blob , объекты File также имеют свойства name и lastModified плюс внутреннюю возможность чтения из файловой системы. Обычно мы получаем объекты File из пользовательского ввода, например, через или перетаскиванием с помощью мыши, в событии dragend .

    Объекты FileReader могут читать из файла или Blob в одном из трёх форматов:

    • Строка ( readAsText ).
    • ArrayBuffer ( readAsArrayBuffer ).
    • URL в формате base64 ( readAsDataURL ).

    Однако, во многих случаях нам не нужно читать содержимое файла. Как и в случае с Blob, мы можем создать короткий URL с помощью URL.createObjectURL(file) и использовать его в теге или . Таким образом, файл может быть загружен или показан в виде изображения, как часть canvas и т.д.

    А если мы собираемся отправить File по сети, то это также легко, поскольку в сетевые методы, такие как XMLHttpRequest или fetch , встроена возможность отсылки File .

    Источник

    How To Read and Process Files with the JavaScript FileReader API

    How To Read and Process Files with the JavaScript FileReader API

    In this article, you will explore the File , FileReader , and FileReaderSync APIs.

    Prerequisites

    If you would like to follow along with this article, you will need:

    • An understanding of JavaScript methods, EventListener , and Promises will be helpful.
    • A code editor.
    • A modern web browser that supports File , FileReader , and FileReaderSync .

    Uploading a File

    First, to get a file from a user, we need to use an element:

    This code will let users upload files from their machines.

    Here’s an example of uploading a file using an HTML :

    form enctype="multipart/form-data" action="/upload" method="post"> input id="input" type="file" /> form> 

    For greater control in handling uploads, you can use JavaScript instead of an HTML to submit the files:

    let file = document.getElementById('input').files[0]; let formData = new FormData(); formData.append('file', file); fetch('/upload/image', method: "POST", body: formData>); 

    Using File Blob Properties

    In modern browsers, Files have Blob properties and functions. These functions allows us to read the file.

    • .text() transforms the file into a stream and then into a string.
    • .stream() returns a ReadableStream .
    • .arrayBuffer() returns an ArrayBuffer that contains the blob’s data in binary form.
    • .slice() allows you to get slices of the file.

    Create a new myFile.txt file with some text:

    Then, create a new file-blob-example.html file:

    !DOCTYPE html> html> body> input type="file" id="input" /> script> const streamToText = async (blob) =>  const readableStream = await blob.getReader(); const chunk = await readableStream.read(); return new TextDecoder('utf-8').decode(chunk.value); >; const bufferToText = (buffer) =>  const bufferByteLength = buffer.byteLength; const bufferUint8Array = new Uint8Array(buffer, 0, bufferByteLength); return new TextDecoder().decode(bufferUint8Array); >; document.getElementById('input').addEventListener('change', function(e)  let file = document.getElementById('input').files[0]; (async () =>  const fileContent = await file.text(); console.log('.text()', fileContent); const fileContentStream = await file.stream(); console.log('.stream()', await streamToText(fileContentStream)); const buffer = await file.arrayBuffer(); console.log('.buffer()', bufferToText(buffer)); const fileSliceBlob = file.slice(0, file.length); const fileSliceBlobStream = await fileSliceBlob.stream(); console.log('.slice() and .stream()', await streamToText(fileSliceBlobStream)); >)(); >); /script> /body> /html> 

    Open file-blob-example.html in your web browser and add the myFile.txt file to the input . In your web developer console, you will see the file contents read out using .text() , .stream() , .buffer() , and .slice() .

    Applying FileReader Lifecycle and Methods

    There are 6 main events attached to FileReader:

    • loadstart : Fires when we start loading a file.
    • progress : Fires when the blob is read in memory.
    • abort : Fires when we call .abort .
    • error : Fires when an error occurs.
    • load : Fires when the read is successful.
    • loadend : Fires when the file is loaded and if error or abort didn’t get called or if load starts a new read.

    To start loading our file we have four methods:

    • readAsArrayBuffer(file) : Reads the file or blob as an array buffer. One use case is to send large files to a service worker.
    • readAsBinaryString(file) : Reads the file as a binary string
    • readAsText(file, format) : Reads the file as USVString (almost like a string), and you can specify an optional format.
    • readAsDataURL(file) : This will return a URL where you can access the file’s content, it is Base64 encoded and ready to send to your server

    Create a new filereader-example.html file that uses readAsDataURL() :

    DOCTYPE html> html> head> style> body  background: #000; color: white; > #progress-bar  margin-top: 1em; width: 100vw; height: 1em; background: red; transition: 0.3s; > style> head> body> input type="file" id="input" /> progress value="0" max="100" id="progress-bar">progress> div id="status">div> script> const changeStatus = (status) =>  document.getElementById('status').innerHTML = status; > const setProgress = (e) =>  const fr = e.target; const loadingPercentage = 100 * e.loaded / e.total; document.getElementById('progress-bar').value = loadingPercentage; > const loaded = (e) =>  const fr = e.target; var result = fr.result; changeStatus('Finished Loading!'); console.log('Result:', result); > const errorHandler = (e) =>  changeStatus('Error: ' + e.target.error.name); > const processFile = (file) =>  const fr = new FileReader(); fr.readAsDataURL(file); fr.addEventListener('loadstart', changeStatus('Start Loading')); fr.addEventListener('load', changeStatus('Loaded')); fr.addEventListener('loadend', loaded); fr.addEventListener('progress', setProgress); fr.addEventListener('error', errorHandler); fr.addEventListener('abort', changeStatus('Interrupted')); > document.getElementById('input').addEventListener('change', (e) =>  const file = document.getElementById('input').files[0]; if (file)  processFile(file); > >); script> body> html> 

    Open filereader-example.html in your web browser and add the myFile.txt file to the input . A progress bar will appear on the screen as the file is processed. If it loads successfully, it will indicate ‘Start Loading’ , ‘Loaded’ , and ‘Finished Loading’ .

    Using FileReaderSync

    FileReader is an asynchronous API because we do not want to block the main thread while reading files. For example, we don’t want our user interface to stop working when the browser is trying to read a very large file. However, there is a synchronous version of FileReader called FileReaderSync . We can only use FileReaderSync in Web Workers. Web workers have their own thread so they won’t block the main thread. FileReaderSync uses the same methods as FileReader :

    • FileReaderSync.readAsArrayBuffer()
    • FileReaderSync.readAsBinaryString()
    • FileReaderSync.readAsText()
    • FileReaderSync.readAsDataURL()

    There are no event handlers because it’s synchronous.

    Conclusion

    In this article, you explored the File , FileReader , and FileReaderSync APIs.

    Take the time to check the browser support for these features to ensure that they are applicable to the users of your projects.

    Continue your learning with additional Web APIs.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Источник

    Читайте также:  Html table data name
Оцените статью